Java: Iterators

So, I am working on a program that includes two types of data: a linked list and an Arraylist.

The linked Iterator list looks like this:

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 a method that does the job of calling 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 that when I call my methods to get my object by their identifier (instance variable), it always captures the NEXT object, and not the object that I want. How to get the current object with both a Linked List and an array?

Please help me!

+3
source share
4 answers

The problem is that you call .next () twice in your loop here:

if (id == xy.next().getId())
{
    return xy.next();
}

next() , , . :

StudentIF nextStudent = xy.next();
if (nextStudent.getId() == id)
{
    return nextStudent;
}
+4

next() , , .

  while (xy.hasNext()) {
        StudentIF tmp = xy.next();
        if (id == tmp.getId()) {
            return tmp;
        }
+6

Each time you use the next () method, it increments the iterator, therefore, by calling

if (id == xy.next().getId())

and

return xy.next();

you are actually increasing the iterator.

It is best to store xy.next (), do whatever comparisons you need, and then return them as follows:

public StudentIF getStudent(int id) {
Iterator<StudentIF> xy = iterator();
while (xy.hasNext()) {
    StudentIF student = xy.next();
    if (id == student.getId()) {
        return student;
    }
}
// Student doesn't exist
return null;

}

+3
source

You call .next()twice.

The solution should only call it once and store it in a variable like this:

 while (xy.hasNext()) {
        StudentIF student = xy.next();
        if (id == student.getId()) {
            return student;
        }
    }
+2
source

All Articles