java – 在Collection中意味着什么?

前端之家收集整理的这篇文章主要介绍了java – 在Collection中意味着什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
什么意思是< 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
原文链接:https://www.f2er.com/java/125350.html

猜你在找的Java相关文章