0

I have this static method declared in class A as follows :

public static boolean staticMethod(List<Object> list)

and I want to call it as follows

List<String> list = new ArrayList<String>();
boolean b = A.staticMethod(list);

Why does it not compile ?

The method staticMethod(List<Object>) in the type ArrayListHelper is not applicable for the arguments (List<String>)

I want to write a generic method doing specific handlings on List objects holding objects from a subclass of Object.

Thanks.

Fred Sullet
  • 371
  • 1
  • 6
  • 18
  • 2
    What you want is for `staticMethod` to accept a `List>`. – Louis Wasserman Jan 03 '16 at 16:03
  • @LouisWasserman Ugly. What he wants is a generic list. The wildcard is sometimes useful but to avoid 90% of the time – Dici Jan 03 '16 at 16:16
  • 2
    @Dici that's what `List>` gets them, and that's the proper way the language provides to get it. Not sure what's "ugly" about that. Did you mean raw types? – Louis Wasserman Jan 03 '16 at 16:17
  • `List>` is pretty much like a raw type isn't it ? It's just specifying explicitely that you don't care about the type, but it has the same properties as a raw type. I would prefer `static void method(List list)`. – Dici Jan 03 '16 at 16:19
  • 2
    @Dici no, it's not like a raw type. It says that the method accepts a generic list, and that its generic type can be anything. Since it doesn't have any other argument that is related to T, and doesn't return a type related to T, it has absolutely no reason to be generic. See http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#reverse-java.util.List- for example, which has the same signature, for the same reason. Just for your information, Louis has designed and implemented a big part of Guava collections. I think he knows how to deal with generic collections :) – JB Nizet Jan 03 '16 at 16:26
  • 1
    @JBNizet yeah, I was going through the same thought process at the moment. If it does not have to return something generic, why even bother. Moreover, I wrote some snippets that show it's indeed different from a raw type. For example, the raw type will let you add anything to the list while the wilcard will prevent this to happen. This solution is actually nice and safe. My bad ! – Dici Jan 03 '16 at 16:31

0 Answers0