Why do some claim that Java's implementation of generics is bad?

后端 未结 13 1971
挽巷
挽巷 2020-11-29 15:53

I\'ve occasionally heard that with generics, Java didn\'t get it right. (nearest reference, here)

Pardon my inexperience, but what would have made them better?

13条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 16:43

    1. Runtime implementation (ie not type erasure);
    2. The ability to use primitive types (this is related to (1));
    3. While the wildcarding is useful the syntax and knowing when to use it is something that stumps a lot of people. and
    4. No performance improvement (because of (1); Java generics are syntactic sugar for castingi Objects).

    (1) leads to some very strange behaviour. The best example I can think of is. Assume:

    public class MyClass {
      T getStuff() { ... }
      List getOtherStuff() { ... }
    }
    

    then declare two variables:

    MyClass m1 = ...
    MyClass m2 = ...
    

    Now call getOtherStuff():

    List list1 = m1.getOtherStuff(); 
    List list2 = m2.getOtherStuff(); 
    

    The second has its generic type argument stripped off by the compiler because it is a raw type (meaning the parameterized type isn't supplied) even though it has nothing to do with the parameterized type.

    I'll also mention my favourite declaration from the JDK:

    public class Enum>
    

    Apart from wildcarding (which is a mixed bag) I just think the .Net generics are better.

提交回复
热议问题