如何在 Java 中迭代整数数组列表的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15865338/
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-10-31 21:06:26  来源:igfitidea点击:

How to iterate elements of an integer arraylist in Java

javaarraysarraylist

提问by Abushawish

I understand that when you iterate a regular array element it is like so:

我知道当您迭代常规数组元素时,它是这样的:

int[] counter = new int[10];

for loop{
   counter[i] = 0;
}

when button clicked{
  counter[0]++; //For example
  counter[6]++;
}

However I'm not understanding how to iterate through elements of an arraylist. If someone could help me understand I'll be appreciative. Thanks!

但是我不明白如何遍历数组列表的元素。如果有人能帮助我理解,我将不胜感激。谢谢!

回答by Benjamin Gruenbaum

The easiest way would be to use a for each loop

最简单的方法是为每个循环使用一个

for(int elem : yourArrayList){
   elem;//do whatever with the element
}

回答by Achintya Jha

for (int i = 0; i < arrayList.size(); i++) {

}

Or

或者

Iterator<Object> it = arrayList.iterator();
while(it.hasNext())
{
    Object obj = it.next();
    //Do something with obj
}

回答by kaysush

Iterating over an array list is really simple.

遍历数组列表非常简单。

You can use either the good old for loopor can use the enhanced for loop

您可以使用旧的for loop,也可以使用enhanced for loop

Good Old for loop

好老的 for 循环

int len=arrayList.size();
for(int i = o ; i < len ; i++){
int a =arrayList.get(i);
}

Enhanced for loop

增强的 for 循环

for(int a : arrayList){
//you can use the variable a as you wish.
}