What's this generics usage in Java? X.method()

前端 未结 5 570
野性不改
野性不改 2021-02-07 06:22

I\'ve read the whole SCJP6 book Sierra and Bates book, scored 88% the exam.

But still, i never heard of how this kind of code works as it\'s not explained in the generic

5条回答
  •  借酒劲吻你
    2021-02-07 06:47

    As the other answers have clarified, it's to help the compiler figure out what generic type you want. It's usually needed when using the Collections utility methods that return something of a generic type and do not receive parameters.

    For example, consider the Collections.empty* methods, which return an empty collection. If you have a method that expects a Map:

    public static void foo(Map map) { }
    

    You cannot directly pass Collections.emptyMap() to it. The compiler will complain even if it knows that it expects a Map:

    // This won't compile.
    foo(Collections.emptyMap());
    

    You have to explicitly declare the type you want in the call, which i think looks quite ugly:

    foo(Collections.emptyMap());
    

    Or you can omit that type declaration in the method call if you assign the emptyMap return value to a variable before passing it to the function, which i think is quite ridiculous, because it seems unnecessary and it shows that the compiler is really inconsistent: it sometimes does type inference on generic methods with no parameters, but sometimes it doesn't:

    Map map = Collections.emptyMap();
    foo(map);
    

    It may not seem like a very important thing, but when the generic types start getting more complex (e.g. Map>>) one kind of starts wishing that Java would have more intelligent type inference (but, as it doesn't, one will probably start writing new classes where it's not needed, just to avoid all those ugly <> =D).

提交回复
热议问题