java – 在Collection中意味着什么?

什么意思是 E在代码集合 E? 这是使用仿制药.检查这个 intro出来.然后不要忘了看这个 tutorial. 以下是一个摘录(比较了一个演员与使用泛型的用法): When you see the code Type, read it as “of Type”; the declaration above reads as “Collection of St

什么意思是< E>在代码集合< E>?

解决方法

这是使用仿制药.检查这个
intro出来.然后不要忘了看这个
tutorial.

以下是一个摘录(比较了一个演员与使用泛型的用法):

When you see the code <Type>,read it
as “of Type”; the declaration above
reads as “Collection of String c.” The
code using generics is clearer and
safer. We have eliminated an unsafe
cast and a number of extra
parentheses. More importantly,we have
moved part of the specification of the
method from a comment to its
signature,so the compiler can verify
at compile time that the type
constraints are not violated at run
time. Because the program compiles
without warnings,we can state with
certainty that it will not throw a
ClassCastException at run time. The
net effect of using generics,
especially in large programs,is
improved readability and robustness.

例如,List的接口是

public interface List<E> { 
    void add(E x);
    Iterator<E> iterator();
}

这意味着您可以构建一个列表,其内容都是相同的显式类型(不仅是Object类型),即使您已经自己定义了类型.所以,如果你创建一个Name类可以写

List<Name> nameList = new List<Name>();

然后使用Name实例填充它,并直接从其中检索Name实例,而不必投射或以其他方式担心它,因为您将始终获得一个Name实例或返回null,而不是一个不同类型的实例.

更重要的是,您无法在此列表中插入与Name实例不同的任何内容,因为它将在编译时失败.

nameList.add(false); //Fails!
nameList.add(new Name("John","Smith")); //Succeeds supposing Name has a 
                                        //firstName,lastName constructor

作者: dawei

【声明】:永州站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

为您推荐

联系我们

联系我们

0577-28828765

在线咨询: QQ交谈

邮箱: xwei067@foxmail.com

工作时间:周一至周五,9:00-17:30,节假日休息

返回顶部