解决方法
以下是一个摘录(比较了一个演员与使用泛型的用法):
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。