I have the following code segment:
public void reorder(int fromIndex, int toIndex) {
getElements().add(toIndex, getElements().remove(fromIndex));
}
Here, the method getElements has the return type List<?>. The remove method has the return type ?, and the add method shows its arguments as int index, ? element. So my assumption was, since the return type of remove method and second argument of add method are the same – ? – the method call must succeed. But, I was wrong, the above code segment results in the error:
The method add(int, capture#17-of ?)
in the type List<capture#17-of ?>
is not applicable for the arguments (int, capture#18-of ?)
Here, I don’t have any direct access to the list, and I don’t know it’s original type returned by getElements method. All I want here is to remove the item at fromIndex and put it at toIndex. So, how do I achieve that? Also is there anything wrong with my understanding of the generics?
Just add a cast that makes that
?concrete:Since you are just rearranging elements within the list, this will never cause any trouble. But I must say there’s something wrong with the design if you are seeing that kind of return value.