Reputation: 7734
I had a line of code which is below.
List<? extends SortKey> sortKeys = new ArrayList();
This caused the warning ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized
. I did some research and found these questions - Collections of generics “Cannot instantiate the type ArrayList” and How can elements be added to a wildcard generic collection?. So I constructed a public List
which looked like the following.
public <T extends SortKey> List<T> sortKeys() {
List<SortKey> keys = new ArrayList<SortKey>();
keys.add(new RowSorter.SortKey( 0, SortOrder.ASCENDING));
keys.add(new RowSorter.SortKey( 1, SortOrder.ASCENDING));
return keys;
}
However when I try to compile this code I get the error, Type mismatch: cannot convert from List<RowSorter.SortKey> to List<T>
. How can I fix this error?
Note
I also found the that the line of code, List<? extends SortKey> sortKeys = new ArrayList<>();
, removes the warning but I do not understand why? I would appreciate if someone took the time to explain that or reference something which would allow me understand it.
Edit
Using the following code fixes the error.
public <T extends SortKey> List<T> sortKeys() {
List<T> keys = new ArrayList<T>();
keys.add((T) new RowSorter.SortKey( 0, SortOrder.ASCENDING));
keys.add((T) new RowSorter.SortKey( 1, SortOrder.ASCENDING));
return keys;
}
However new warning are produced which state Type safety: Unchecked cast from RowSorter.SortKey to T
.
Upvotes: 1
Views: 2852
Reputation: 81
For the first question, you're missing the generic braces on new ArrayList()
-> new ArrayList<>()
.
For the second question, you're trying to use SortKey (which doesn't extend from SortKey, of course) as the list type.
Not sure why you're storing them like that, though, because you can store subclasses by the superclass type.
Upvotes: 1