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

后端 未结 13 1969
挽巷
挽巷 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:33

    Bad:

    • Type information is lost at compile time, so at execution time you can't tell what type it's "meant" to be
    • Can't be used for value types (this is a biggie - in .NET a List really is backed by a byte[] for example, and no boxing is required)
    • Syntax for calling generic methods sucks (IMO)
    • Syntax for constraints can get confusing
    • Wildcarding is generally confusing
    • Various restrictions due to the above - casting etc

    Good:

    • Wildcarding allows covariance/contravariance to be specified at calling side, which is very neat in many situations
    • It's better than nothing!

提交回复
热议问题