MAXGEN
MAXGEN

Reputation: 755

Java Using iterator for arraylist how do you get index

If i'm using Iterator how do i get the index in which my condition is met? iterator.next() gives me one after so I can minus one but I figure this is right way to do this?

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;

What I found to be correct code for my situation.

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 ;


    }

Upvotes: 0

Views: 3042

Answers (3)

assylias
assylias

Reputation: 328598

You probably get an unexpected value for tempposition because you call next twice in your loop. It should probably look like this instead:

Item item = iterator.next(); // call next only once here
if (item.getTitle().equals("Something")) {
    tempposition = item.getPosition();
}

Upvotes: 2

Kalin Varbanov
Kalin Varbanov

Reputation: 363

From http://www.tutorialspoint.com/java/java_using_iterator.htm

int nextIndex() Returns the index of the next element. If there is not a next element, returns the size of the list. int previousIndex() Returns the index of the previous element. If there is not a previous element, returns -1.

Upvotes: 0

Tyler
Tyler

Reputation: 18177

You have to keep track yourself

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;

Upvotes: 0

Related Questions