如果我正在使用Iterator,我如何获得符合条件的索引? iterator.next()
给了我一个,所以我可以减一,但我认为这是正确的方法吗?
public static int getSomething()
int tempposition = 1;
Iterator<Item> iterator = data.iterator();
while (iterator.hasNext())
{
if (iterator.next().getTitle().equals("Something"))
{
tempposition = iterator.next().getPosition();
}
}
return tempposition - 1;
我发现我的情况是正确的代码。
public static int getSomething()
{
int tempposition = 1;
Iterator<Item> iterator = data.iterator();
while (iterator.hasNext())
{
Item item = iterator.next();
if (item.getTitle().equals("Something"))
{
tempposition = item.getPosition();
}
}
Log.d(TAG, "tempposition is " + tempposition );
return tempposition ;
}
答案 0 :(得分:2)
您可能会为tempposition
获得意外值,因为您在循环中调用next
两次。它应该看起来像这样:
Item item = iterator.next(); // call next only once here
if (item.getTitle().equals("Something")) {
tempposition = item.getPosition();
}
答案 1 :(得分:0)
来自http://www.tutorialspoint.com/java/java_using_iterator.htm
int nextIndex()
返回下一个元素的索引。如果没有下一个元素,则返回列表的大小。 intpreviousIndex()
返回前一个元素的索引。如果没有前一个元素,则返回-1
。
答案 2 :(得分:0)
你必须自己跟踪
public static int getSomething()
int tempposition = 1;
int index = 0;
Iterator<Item> iterator = data.iterator();
while (iterator.hasNext())
{
if (iterator.next().getTitle().equals("Something"))
{
tempposition = iterator.next().getPosition();
}
index++;
}
return tempposition - 1;