Java 为每个迭代 ArrayList 的循环获取 a 的当前索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20961617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:35:27  来源:igfitidea点击:

Get the current index of a for each loop iterating an ArrayList

javaarraylistforeachindexing

提问by Renaud is Not Bill Gates

I'm iterating an ArrayListusing the for each loop, but I don't know how to get the current index where the loop is.

我正在迭代ArrayList使用 for each 循环,但我不知道如何获取循环所在的当前索引。

I did Google it, but I couldn't find anything helpful.

我做了谷歌,但我找不到任何有用的东西。

Please, if someone could tell me how to get the current index, I'll be grateful.

请,如果有人能告诉我如何获得当前索引,我将不胜感激。

采纳答案by Doorknob

Just use a traditional for loop:

只需使用传统的 for 循环:

for (int i = 0; i < yourArrayList.size(); i ++) {
    // i is the index
    // yourArrayList.get(i) is the element
}

回答by Zak

To steal doorknobs answer but make a change that otherwise would drive me nuts like a pirate:

窃取门把手的答案但做出改变,否则会像海盗一样让我发疯:

int arraySize = yourArrayList.size();
for (int i = 0; i < arraySize; i ++) {
    // i is the index
    // yourArrayList.get(i) is the element
}

alternatively

或者

int currentPosition = 0;
for (myItemType myItem :myArrayList) {
    // do stuff

    currentPosition++;
}

回答by Reut Sharabani

Use a traditional loop. For-each statements in java do not promise an order over the collection. The only way to actually know the index is to query the list on every iteration.

使用传统循环。Java 中的 For-each 语句不承诺对集合的顺序。真正知道索引的唯一方法是在每次迭代时查询列表。

for(int i=0; i<list.size; i++){
    // you have your index, i
    // the item is at list.get(i)
}

Relying on the iterator() implementation you can also use an alternative (+1 Zak in the comments):

依靠 iterator() 实现,您还可以使用替代方法(评论中的 +1 Zak):

int position = 0;
for(Item i : list){

    // do stuff with `i`

    // increase position as the last action in the loop
    position++;
}

From the docs: Iterator<E> iterator() Returns an iterator over the elements in this list in proper sequence

从文档: Iterator<E> iterator() Returns an iterator over the elements in this list in proper sequence

Here is why I usuallydon't use the short form of for:

这就是为什么我通常不使用以下缩写形式的原因for

import java.util.ArrayList;
import java.util.Iterator;


public class MyList<T> extends ArrayList<T> {
    // the main function to run the example
    public static void main(String[] args){
        // make a list of my special type
        MyList<Integer> list = new MyList<Integer>();

        // add 10 items to it
        for (int i =0; i<10; i++){
            list.add(i);
        }

        // print the list using the for-each mechanism (it's actually an iterator...)
        for (Integer i : list){
            System.out.println(i);
        }
    }

    // I like lists that start at 3!
    // make my list return an iterator in the middle of the list...
    @Override
    public Iterator<T> iterator(){
        return this.listIterator(3);

    }

}

Obviously, you'd expect having the first item on the first iteration, and this is clearly not the case because an iterator can be implemented in many ways and Java's foreachis depending on the underlying iteratorimplemetation.

显然,您会期望在第一次迭代中拥有第一项,而这显然不是这种情况,因为迭代器可以通过多种方式实现,而 Javaforeach则取决于底层iterator实现。

Also, you have to use position++in the end of your loop which is probablyerror-prone (don't know, don't usually use it..).

此外,您必须position++在循环结束时使用这可能容易出错(不知道,通常不使用它......)。

That said, it does improve readability like mentioned in this stackoverflow questionabout Java's foreach.

也就是说,它确实提高了可读性,就像这个关于 Java 的 foreach 的stackoverflow问题中提到的那样。

For more information, see How does the Java for each loop work?.

有关更多信息,请参阅每个循环的 Java 是如何工作的?.

回答by Maelo

If it's iterating a List, you can use the method indexOf(), example:

如果它正在迭代一个列表,你可以使用 indexOf() 方法,例如:

List<Animal> animals = new ArrayList<Animal>();
Animal a = new Animal();
a.setAnimalCode(1);
animals.add(a);

a = new Animal();
a.setAnimalCode(35);
animals.add(a);

a = new Animal();
a.setAnimalCode(12);
animals.add(a);

for(Animal a: animals)
   if(animal.getAnimalCode()==35)
      System.out.println("Index of chosen one: "+animals.indexOf(a));

Index of chosen one: 2

已选索引:2

回答by Omar Sebres

You can use list.indexOf(objectYouWantToFind);to get its index if it is in the container else you will receive -1as a result.

list.indexOf(objectYouWantToFind);如果它在容器中,您可以使用它来获取它的索引,否则您将收到-1

回答by Aayush Shrivastava

Kind of a hack, but you can surely have an index in a for each loop :

有点像 hack,但你肯定可以在 for each 循环中有一个索引:

public class Counter{
  private Integer i;
  public Counter(Integer i) { this.i = i; }
  public void incrementOne(){ this.i = getI() + 1; }
  //getter and setter for i
}

And, somewhere else in your for each loop :

而且,在你的 for each 循环中的其他地方:

Alien.java

外星人.java

Counter counter = new Counter(0);
List<String> list = new ArrayList<>();
//have some values in the list
list.forEach(i-> {
  //i will have the value and the counter will have the count!
  System.out.println(counter.getI());
  counter.incrementOne();
});

Otherwise, you always have a list.indexOf(i), where i is each object in the list. :P

否则,您总是有一个 list.indexOf(i),其中 i 是列表中的每个对象。:P