Java为arraylist使用iterator如何获得索引

时间:2014-03-18 17:23:34

标签: java arraylist iterator

如果我正在使用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 ;


    }

3 个答案:

答案 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()       返回下一个元素的索引。如果没有下一个元素,则返回列表的大小。       int previousIndex()       返回前一个元素的索引。如果没有前一个元素,则返回-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;