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

Is there a way to get the id of a list item so I can get it later via list.get(index)

using

 for(Object obj: o) 

construction

Define only local var and manually increase it? Anything easier?

+4
source share
4 answers

No, the for-each loop does not track the index. You can use a regular indexed loop or do something like this:

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

This is dangerous because break / continue will make idx not synchronized, so use it infrequently and only when the body is simple and only a few lines away.

If the elements are different, List.indexOf will also work, albeit in O(N) , and at this point you may consider a Set (unordered, but guaranteed report).


It should also be said that sometimes using listIterator() also facilitates the need for an explicit index during iteration.

A ListIterator supports add , Set and remove operations.

This is another clear advantage. List has redundant arrays as iteration mechanism progresses.

+7
source

The simple answer is No.

The best I can think of is to combine iteration and indexing as follows:

 int idx = 0; for (Iterator<Object> it = list.iterator(); it.hasNext(); idx++) { Object o = it.next(); // ... } 

This approach has the advantage that break and continue will not spoil idx calculations.

On the other hand, if list is an ArrayList and you want to track the index, you are probably best off using the option

 for (idx = 0; idx < list.size(); idx++) { Object o = list.get(idx); // ... } 
+5
source

This question has not been formulated very well, but from what I can say, would you like to find the position of a specific Object inside a List<Object> , and then get it later through this index?

First of all, if you know the Object you are looking for, you will not need to find it in the List , since you already have it.

However, you can easily do something like this:

 int index = -1; for (int i = 0; i < list.size(); i++) { if (list.get(i).equals(myObject)) { index = i; break; } } 

But I would look at your application to determine if this is really necessary for you.

+2
source

You need to use:

 list.indexOf(o); 

Documentation here

@Eugene I see that you mention in the comment to another answer that you plan to store the index of the object (with the object in the object in question?), Which is probably not a good idea, be very careful as the index of objects can change.

+2
source

Source: https://habr.com/ru/post/1310124/


All Articles