jesse
jesse

Reputation: 117

Need help stepping through a java iterator

Say I have already created an iterator called "iter" and an arraylist called "database". I want to be able to look through the arraylist and see if any element in the arraylist is equal to a String called "test". If it is, then I would like to add the element to another list.

while(iter.hasNext()) {
    if(database.next() == test) { 
        database.next().add(another_list);
    }
}

What am I doing wrong? I'm completely new to iterators in java. Do I need to write my own iterator class? Any code examples would be greatly appreciated. Thanks

Upvotes: 1

Views: 279

Answers (2)

templatetypedef
templatetypedef

Reputation: 372674

The problem with your code is that every time you call .next(), it advances the iterator forward to the next position. This means that this code

if(database.next() == test) { 
    database.next().add(another_list);
}

Won't work as intended, because the first call to database.next() will not give back the same value as the second call to database.next(). To fix this, you'll want to make a temporary variable to hold on to the new value, as seen here:

while(iter.hasNext()) {
    /* type */ curr = iter.next();
    if(curr == test) { 
        curr.add(another_list);
    }
}

(Filling in the real type of what's being iterated over in place of /* type */)

In many cases, though, you don't need to use iterators explicitly. Most of the Collections types implement the Iterable interface, in which case you can just write

/* container */ c;
for(/* type */ curr: c) {
    if(curr == test) { 
        curr.add(another_list);
    }
}

Hope this helps!

Upvotes: 2

Aravind Yarram
Aravind Yarram

Reputation: 80166

if(database.contains("test"))
{
   another_list.add("test");
}
  1. you can use the built in method contains(...)
  2. you should use equals(...) for data comparisions
  3. look at the javadoc to see if there is already a method present for your purpose

Upvotes: 2

Related Questions