My question is based off the answer to a previous question:
Why we can't do List<Parent> mylist = ArrayList<child>();
I have a function that sorts a list of children that is passed to it based on the parameters in the parent function. Since there are many different types of children I wrote a function that receives a generic parent type.
void sort(ArrayList<? extends Parent> passedList)
Later in the function, I would like to swap two members (i and j) of the ArrayList, but I cannot figure out how. I have tried:
Parent swap;
swap = passedList.get(i);
passedList.set(i,passedList.get(j));
passedList.set(j,swap);
However this will not compile and it says the types are not compatible in the set function. The type that I receive from get is Parent, but set expects a type of (? extends Parent). I have also tried declaring swap as ? extends Parent swap;
or by casting as in
passedList.set(i,(? extends Parent)passedList.get(j));
It seems like it should be possible seeing as how we can guarantee that the object returned by passedList.get() is the right type to belong in the arraylist.