Snow_Mac
Snow_Mac

Reputation: 5797

Java: Iterators

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!

Upvotes: 3

Views: 1862

Answers (4)

insumity
insumity

Reputation: 5479

You use the next() method twice, that's probably why.

Try this

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

Upvotes: 6

Brian Geihsler
Brian Geihsler

Reputation: 2087

The problem is that you're calling .next() twice in your loop here:

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

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:

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

Upvotes: 4

Pablo Fernandez
Pablo Fernandez

Reputation: 105258

You are calling .next() twice.

The solution should be calling it only once and saving it in a variable like this:

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

Upvotes: 2

Dimitar
Dimitar

Reputation: 2402

Everytime you use the next() method it increments the iterator, so by calling

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

and

return xy.next();

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:

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;

}

Upvotes: 3

Related Questions