Java 如何初始化一个迭代器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1251544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to init an iterator
提问by mkind
i just intent to initialize an iterator over a generic linked list like that (generic typ T seems to be erased in here since the site interpret it as tag)
我只是打算在这样的通用链表上初始化迭代器(通用 typ T 似乎在这里被删除,因为站点将其解释为标签)
public <T> LinkedList<T> sort(LinkedList<T> list){
Iterator<T> iter = new list.iterator();
...
but i got the error:
但我得到了错误:
"list cannot be resolved"
“列表无法解析”
what's wrong?
怎么了?
采纳答案by Jon Bright
To further clarify Mykola's correct answer: you're trying to create a new object of the class list
. So you just want to call list.iterator()
(which, somewhere inside it, is itself doing new Iterator
or something like it and returning that to you).
为了进一步澄清 Mykola 的正确答案:您正在尝试创建类的新对象list
。所以你只想调用list.iterator()
(它在它内部的某个地方,它本身正在做new Iterator
或类似的事情并将其返回给你)。
Since you're clearly using Java 5 or above, though, the better way might be instead of doing
但是,由于您显然使用的是 Java 5 或更高版本,因此更好的方法可能是不要这样做
public <T> LinkedList<T> sort(LinkedList<T> list){
Iterator<T> iter = new list.iterator();
while (iter.hasNext()){
T t = iter.next();
...
}
}
instead doing this:
而是这样做:
public <T> LinkedList<T> sort(LinkedList<T> list){
for (T t : list){
...
}
}
Still better, don't write that method at all and instead use
更好的是,根本不要写那个方法,而是使用
Collections.sort(list);
回答by Mykola Golubyev
Remove the new
keyword:
删除new
关键字:
Iterator<T> iter = list.iterator();
回答by Niger
The word followed by new operator must be a Class name. Here list.iterator() is already returning a Object. So at this point new is uncessary.
new 运算符后面的单词必须是类名。这里 list.iterator() 已经返回了一个对象。所以在这一点上 new 是不必要的。