[英]Java ListIterator/Iterator Type
I have a code snippet as shown below: 我有一个代码片段,如下所示:
ArrayList<Integer> a = new ArrayList<Integer>();
ListIterator<Integer> p = a.listIterator();
However, I noticed that you don't really need to specify the for the ListIterator so the code works same without it: 但是,我注意到你并不真的需要为ListIterator指定,所以代码在没有它的情况下工作相同:
ArrayList<Integer> a = new ArrayList<Integer>();
ListIterator p = a.listIterator();
I think the same is als true for Iterator. 我认为Iterator也是如此。 So my question is when do I have to specify the type for a ListIterator/Iterator ?
所以我的问题是我何时必须指定ListIterator / Iterator的类型? Is it something optional that can be used be more verbose ?
它是可选的,可以使用更冗长吗?
The reason to specify the generic type for the iterator is so you can extract the item it retrieves without casting. 为迭代器指定泛型类型的原因是,您可以提取它检索的项目而不进行强制转换。 This adds a bit of compile-time type safety with no additional significant overhead, so I see no reason not to do this.
这增加了一点编译时类型的安全性,没有额外的显着开销,所以我认为没有理由不这样做。
What you are referring to, is called generics
. 你所指的是所谓的
generics
。 It's a really powerful tool, which - amongst others - gives you type safety for collections in compile-time. 它是一个非常强大的工具,其中包括在编译时为集合提供类型安全性。
Take a look at Java Denerics documentation pages to learn when, why and how you should use them. 查看Java Denerics文档页面 ,了解何时,为何以及如何使用它们。
Now, back to your example - this code: 现在,回到你的例子 - 这段代码:
Iterator it1 = a.iterator();
Iterator<Integer> it2 = a.iterator();
it1.next(); // Compiler will assume, that this returns `Object`
// because you did not define the type of the collection element
// for the Iterator.
it2.next(); // Compiler will assume, that this returns `Integer`
// because you said so in declaration.
The purpose of providing a type argument for an Iterator< T >/List< T > is type-safety ,ie the compiler can check at compile time if there is a mismatch between the type the iterator/list can handle and what the programmer expects it to handle. 为Iterator <T> / List <T>提供类型参数的目的是类型安全,即编译器可以在编译时检查迭代器/列表可以处理的类型与程序员期望的类型之间是否存在不匹配它要处理。
Ex: 例如:
List aList = new ArrayList();
Iterator it = aList.iterator();
String s = (String)it.next() //compiles even if it iterates over a list of Integers
List<Integer> aList = new ArrayList<Integer>();
Iterator<Integer> it = aList.iterator();
String s = it.next() //compilation error
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.