Adding to a Generic Set passed into a method
collections, generics, java
Solution
Good research, you were almost there. You just need to add an upper bound to `T`.
private <T extends Animal> boolean addObject(T toAdd, T defVal, Set<? super T> vals)
Problem
Let us say I have the following classes: - Animal - Cat - Dog - Cow Animal is the base class, cat, dog, and cow each subclass it. I now have a `Set<Cat>`, `Set<Dog>` and `Set<Cow>` each of these are used in the same way, so it makes sense to make a generic function to operate on them: ``` private boolean addObject(Animal toAdd, Animal defVal, Set<? extends Animal> vals) ``` This works great, I can freely pass in my Sets with no problem. The problem appears: I can't attempt to add the Animal toAdd to parameter vals. Googling reveals that if I change the method to read: ``` private boolean addObject(Animal toAdd, Animal defVal, Set<? super Animal> vals) ``` I will be able to add the Animal to parameter vals. This works, except now, I can't pass in my subclassed my Sets of Cats, Dogs, and Cows. Further research tells me that the following works, with no warnings to boot: ``` private <T> boolean addObject(T toAdd, T defVal, Set<? super T> vals) ``` The problem being, I need to be able to perform method calls that Animal's all have. This is easily gotten around using a simple cast: ``` ((Animal)toAdd).getAnimalType() ``` Is there any way around this problem so I can keep the generic functionality, and not require casting? Aside from making my Sets all Sets of the Base Type, Animal in the case of this example?