开发者

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

开发者 https://www.devze.com 2022-12-30 12:30 出处:网络
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)

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开发者_StackOverflow local var and manually incrementing it? Anything simpler?


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.


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 won't mess up the idx calculations.

On the other hand, if the list is an ArrayList and you want to keep track of the index, you are probably better just using a variation of

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


This question is not worded very well, but from what I can tell you would like to find the position of a specific Object within a List<Object>, and then retrieve it later via that index?

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

That said, you could 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 take a second look at your application to determine whether this is really something that is necessary for you to do.


You need to use:

list.indexOf(o);

The documentation is here

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号