为什么有人声称Java的泛型实现不好? [英] Why do some claim that Java's implementation of generics is bad?
本文介绍了为什么有人声称Java的泛型实现不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
偶尔有人听说,用泛型来说,Java并没有得到正确的答案。 (最近的参考,这里)
请原谅我的经验不足,但是会让他们变得更好吗?
- 类型信息在编译时会丢失,所以在执行时你不能说出它的意思是什么类型的元素
- 不能用于值类型(这是一个biggie - 在.NET中, List< byte> 确实由
- 调用泛型方法的语法太糟糕了(IMO)
- 通配符通常很混乱
- 由于上述操作等原因而导致各种限制
好:
- 通配符允许在调用端指定协变/这在很多情况下非常整洁
- 总比没有好!
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?
解决方案
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<byte>
really is backed by abyte[]
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!
这篇关于为什么有人声称Java的泛型实现不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文