【发布时间】:2019-04-01 15:39:32
【问题描述】:
我在使用 foreach 显示我的 LinkedList 时遇到问题。
当我想显示我的 LikedList 时,我的列表中出现一个错误,告诉我必须使用迭代器。代码如下:
public class Set {
private LinkedList <Integer> elements;
public Set () {
this.elements = new LinkedList <Integer> ();
}
public static void main (String [] args) {
Set test = new Set ();
test.add (8);
test.add (2);
test.add (7);
for (int e: test) {
}
}
所以我使用了一个迭代器进行显示,但一条消息告诉我,我的迭代器未针对方法集定义。
代码如下:
public class Set {
private LinkedList <Integer> elements;
public Set () {
this.elements = new LinkedList <Integer> ();
}
public static void main (String [] args) {
Set test = new Set ();
test.add (8);
test.add (2);
test.add (7);
Iterator <Integer> iterator = test.iterator ();
while (iterator.hasNext ()) {
System.out.println (iterator.next ());
}
}
如果你能帮我解决这个问题,那对我有很大帮助。
(我试图在 Set() public 中定义“Iterator <Integer> iterator = this.elements.iterator ();”,并在手中这样调用它但没有成功“while (iterator.hasNext ()) {
System.out.println (iterator.next ());
}”)
提前谢谢你,美好的一天
【问题讨论】:
-
已经有一个
Set接口。请重命名您的班级。令人困惑。 -
你想达到什么目的?你有一个名为 Set 的类,你在里面使用 LinkedList,为什么?举个例子,你为什么不使用 HashSet?
-
@Michael Dz,因为 LinkedList 的使用是强加给我的
-
你认为任何包含一些集合的类默认是可迭代的?
标签: java linked-list iterator