Reputation: 5
Can someone explain to me why this is okay:
public static void main(String args[]) {
List<Integer> integers = new ArrayList<>();
test(integers);
}
public static void test(List list) {
}
But this creates the error in the comment:
public static void main(String args[]) {
List<List<Integer>> integers = new ArrayList<>();
test(integers);
//'test(java.util.List<java.util.List>)' cannot be applied to '(java.util.List<java.util.List<java.lang.Integer>>)'
}
public static void test(List<List> lists) {
}
In my understanding, in both cases, the program casts a parameterized type to a generic type, but it only works in the first case. Why is this and how do I go about making a method with a parameter like the second example that could take any list of lists as input?
Upvotes: 0
Views: 48
Reputation: 198023
What you're looking for is
public static <T> void test(List<List<T>> lists) {
}
or
public static void test(List<? extends List<?>> lists) {
}
Don't ever have List
without a <
after it, except when importing it. It has strange properties and removes type safety. Having List<List>
puts the compiler into a weird state where it's trying to have some level of type safety and some not.
Upvotes: 4