在java 5中引入了泛型的原因 [英] reason generics were introduced in java 5

查看:89
本文介绍了在java 5中引入了泛型的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释泛型在Java中引入的原因是什么?



据我了解,它们是为了避免意外地将错误类型的对象添加到集合中而引入的。



我有点像收集的泛型,但不知道为什么他们也被添加到其他类。我已经看到了一些泛型类,它们让你头部受伤,眼睛流血。

那么引入泛型的原因是什么(主要是针对非集合)?



TIA!

解决方案

b
$ b Java通过一种称为类型擦除的机制实现了它的泛型,它在编译时用一个非泛型定义有效地替换了泛型定义。之所以这样做是为了保持API在1.4和1.5之间的兼容性 - 集合API可能已经被更新,但如果你在1.5中以非通用的方式访问它,那么它的工作原理是相同的。



不同之处在于,如果您希望某个集合仅包含特定类型的对象,则可以在API中明确地编码该需求,并避免出现问题,例如接收其中包含错误类型对象的列表,以及还需要明确地转换这些对象,使您的代码更易于阅读,而且不易出错。



您将使用泛型的原因与它们的时间基本相同与集合一起使用 - 当你需要说某个对象是其他对象的组合时,但是该组合可能存在一系列可能的类型,并且一旦约束这些新对象的添加就意味着一个与其他对象不相似的新组合类型类似的复合材料。也就是说,字符串列表类型与整数列表类似,但它们不再彼此兼容。



其中一个例子是 Future 您在等待异步结果的位置。 Future 类封装了异步结果的概念,但特定类型的 Future ,比如 Future< String> futher指定了您可以预期的结果类型 - 并使其与 Future 不同。


Can someone explain what were the reasons generics were introduced in Java?

As far as I understand they were introduced so that you don't accidentally add the wrong type of object to a collection.

I kind of like the generics for collection but can't see why they were added for other classes too. I have seen some generic classes that make your head hurt and your eyes bleed.

So what are all the reasons generics were introduced (mainly for non collections)?

TIA!

解决方案

Essentially type safety and convenience.

Java implements its generics by a mechanism known as type erasure which effectively replaces the generic definition with a non-generic definition at compile time. The reason this was done was to maintain API compatability between 1.4 and 1.5 - the collections API may well have been updated but if you accessed it in a non-generic way in 1.5 it would work the same.

The difference was that if you intended a collection to only contain particular types of objects you could explictly encode that requirement in your APIs and avoid issues such as receiving a list with the wrong type of objects in it - and also the need to have to explictly cast those objects making your code simpler to read and less error prone.

You would use the generics for essentially the same reasons as when they are used with collections - when you need to say that an object is a composite of other objects, but that there may be a range of types possible for that composition and that once bound the addition of these new objects implies a new composite type disimilar to other similar composites. That is to say a list of strings is similar in type to a list of integers but they are no longer compatible with each other.

One example of this is in the Future where you are waiting for an asynchronous result. The Future class encapsulates the concept of the asynchronous result, but the specific type of Future such as Future<String> futher specifies what type of result you can expect - and makes it distinct from Future<Integer>.

这篇关于在java 5中引入了泛型的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆