Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for (Object object : list) [java] and index element

Tags:

java

loops

list

Is there a way to get an element id of a list to get it later through list.get(index)

when using

for(Object obj: o)

construction

Only define a local var and manually incrementing it? Anything simpler?

like image 557
EugeneP Avatar asked May 18 '10 14:05

EugeneP


People also ask

How will you get the index of an object in a list?

Use List Comprehension and the enumerate() Function to Get the Indices of All Occurrences of an Item in A List.

How do you get the index of an element in a list in Java?

indexOf() in Java. The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Syntax : public int IndexOf(Object o) obj : The element to search for.

Can we use index in list in Java?

The get() method of ArrayList in Java is used to get the element of a specified index within the list. Parameter: Index of the elements to be returned. It is of data-type int. Return Type: The element at the specified index in the given list.

How do you find the index of an object in an ArrayList?

The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().


1 Answers

No, for-each loop doesn't keep track of index. You can either use a regular indexed loop, or do something like this:

int idx = 0;
for (Object o : list) {
   ...
   idx++;
}

This is risky since break/continue will make idx goes out of sync, so do use this infrequently, and only when the body is simple and only a few lines long.

If the elements are distinct, List.indexOf would also work, albeit at O(N), and at that point you may want to consider a Set (unordered, but guaranteed distinct).


It should also be said that sometimes using a listIterator() also alleviates the need of an explicit index while iterating.

A ListIterator supports add, set and remove operations.

This is another clear advantage List has over arrays as far as iteration mechanism goes.

like image 174
polygenelubricants Avatar answered Sep 19 '22 18:09

polygenelubricants