0

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?

  • I'll suggest you to read this post https://www.baeldung.com/java-generics and also this answer of raw types in Java https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – mini Jun 02 '22 at 17:38

1 Answers1

4

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413