Java:迭代器
因此,我正在开发一个涉及两种数据类型的程序:链表和数组列表。
链接列表迭代器如下所示:
private class NodeIterator implements Iterator<StudentIF> {
private Node curr;
public NodeIterator(Node head) {
curr = head;
}
public void remove() { }
public boolean hasNext() {
if (curr == null)
return false;
return true;
}
public StudentIF next() {
Node temp = curr;
curr = curr.getNext();
return temp.getData();
}
} // end class NodeIterator
我调用 ArrayList 迭代器方法/类。
MyArrayListName.iterator();
下面是执行调用迭代器工作的方法:
public StudentIF getStudent(int id) {
Iterator<StudentIF> xy = iterator();
while (xy.hasNext()) {
if (id == xy.next().getId()) {
return xy.next();
}
}
// Student doesn't exist
return null;
}
我的问题是,当我调用方法通过 id(实例变量)获取对象时,它总是获取 NEXT 对象,而不是我想要的对象。如何通过链接列表和数组列表获取当前对象?
请帮我!
So I'm working on a program that involves two datatypes: a linked list and a Arraylist.
The linked List Iterator looks like:
private class NodeIterator implements Iterator<StudentIF> {
private Node curr;
public NodeIterator(Node head) {
curr = head;
}
public void remove() { }
public boolean hasNext() {
if (curr == null)
return false;
return true;
}
public StudentIF next() {
Node temp = curr;
curr = curr.getNext();
return temp.getData();
}
} // end class NodeIterator
and I call the ArrayList Iterator method/class.
MyArrayListName.iterator();
Here's the method that does the work of calling the iterators:
public StudentIF getStudent(int id) {
Iterator<StudentIF> xy = iterator();
while (xy.hasNext()) {
if (id == xy.next().getId()) {
return xy.next();
}
}
// Student doesn't exist
return null;
}
My problem is when I call my methods to get my object by their id(instance variable), it always grabs the NEXT object, not the object I want. How do I get the current object with both the Linked List and the Array list?
Please help me!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您使用
next()
方法两次,这可能就是原因。试试这个
You use the
next()
method twice, that's probably why.Try this
问题是您在循环中调用 .next() 两次:
调用 next() 两次将使迭代器前进两次,这不是您想要的。您需要将下一个保存在临时变量中,如下所示:
The problem is that you're calling .next() twice in your loop here:
Calling next() twice will advance your iterator twice which isn't what you want. You need to save the next off in a temporary variable like this:
每次使用 next() 方法时,它都会递增迭代器,因此通过调用
,
您实际上会递增迭代器。
最好的选择是存储 xy.next(),进行所需的任何比较,然后按如下方式返回:
}
Everytime you use the next() method it increments the iterator, so by calling
and
you're actually incrementing the iterator.
Your best bet is to store xy.next(), make any comparisons you need and then return it as follows:
}
您正在调用
.next()
两次。解决方案应该只调用它一次并将其保存在如下变量中:
You are calling
.next()
twice.The solution should be calling it only once and saving it in a variable like this: