开发者

Need help stepping through a java iterator

Say I have already created an iterator call开发者_高级运维ed "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


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!


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜