why do we need the pure <?> in Java?

arminvanbuuren :

why do we need the pure <?> in Java? Does anything passed can only be used as Object ? So it's the same useful as any class casted to Object (only 9 methods could be available)

Thanks


I mean, if you have List< ? > list, you can only use items as Object. This means list.get(0) gives you Object and nothing more. Yes, also I can store to there anything, but is it useful for you? It's like you have a good an expensive thing and put it to a garbage bin. The only you can get from a trash bin is trash. As well you can put any good object of any class to List but get only Object from there with only 9 methods.

Oleksandr Pyrohov :

There are two scenarios where an unbounded wildcard is a useful approach:

  • If you are writing a method that can be implemented using functionality provided in the Object class.

  • When the code is using methods in the generic class that don't depend on the type parameter.
    For example, List.size, or List.clear. In fact, Class<?> is so often used because most of the methods in Class<T> don't depend on T.

For example, see Collections.swap method:

public static void swap(List<?> list, int i, int j) {
    final List l = list;
    l.set(i, l.set(j, l.get(i)));
}

Knowing the type does not aid in swapping two elements within a List,  so an unbounded wildcard is used. You pass in a List - any List - and the method swaps the indexed elements. There is no type parameter to worry about.

For more information, see: Unbounded Wildcards.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=88081&siteId=1