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?
Use List Comprehension and the enumerate() Function to Get the Indices of All Occurrences of an Item in A List.
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.
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.
The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With