遍历 ArrayList<T> java?

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

iterate through ArrayList<T> java?

javaandroid

提问by Mina Gabriel

I'm learning Androidand Javai have created a class let's say like this

我正在学习AndroidJava我已经创建了一个类,让我们这样说

 class x(){
    public int a; 
    public string b;
 }

and then i initiate a list of this class and then added values to its properties like this

然后我启动这个类的列表,然后像这样向它的属性添加值

public ArrayList<x> GetList(){

List<x> myList = new ArrayList<x>();

    x myObject = new x();
    myObject.a = 1; 
    myObject.b = "val1";
     mylist.add(x);

    y myObject = new y();
    myObject.a = 2; 
    myObject.b = "val2";
     mylist.add(y);

return myList;
}

My Question is how can i loop through what GetList() return

我的问题是如何遍历 GetList() 返回的内容

i have tried

我试过了

ArrayList<x> list = GetList();
Iterator<x> iterator = list.iterator();

but i don't know if this is the right way of doing this, plus i don't know what to do next i have added a breakpoint on the Iterator but it seemed to be null , the list have values thought

但我不知道这是否是这样做的正确方法,而且我不知道接下来要做什么我在 Iterator 上添加了一个断点但它似乎是 null ,该列表有值认为

采纳答案by Caleb Brinkman

There are two ways to do this:

有两种方法可以做到这一点:

  1. A forloop
  2. Using the iteratormethod.
  1. 一个for循环
  2. 使用iterator方法。

forloop:

for环形:

for(x currentX : GetList()) {
    // Do something with the value
}

This is what's called a "for-each" loop, and it's probably the most common/preferred method of doing this. The syntax is:

这就是所谓的“for-each”循环,它可能是执行此操作的最常见/首选方法。语法是:

for(ObjectType variableName : InCollection)

for(ObjectType variableName : InCollection)

You could also use a standard forloop:

您还可以使用标准for循环:

ArrayList<x> list = GetList();
for(int i=0; i<list.size(); i++) {
     x currentX = list.get(i);
     // Do something with the value
 }

The syntax for this is:

其语法是:

for(someStartingValue; doSomethingWithStartingValue; conditionToStopLooping)

for(someStartingValue; doSomethingWithStartingValue; conditionToStopLooping)

iteratormethod:

iterator方法:

Iterator<x> iterator = GetList().iterator();
while(iterator.hasNext()) {
    x currentX = iterator.next();
    // Do something with the value
}

回答by wmora

You can loop through your array with a for-each loop:

您可以使用 for-each 循环遍历数组:

for (x item: GetList()) {
    doSomethingWithEachValue(item);
}

回答by Mark

I guess you can iterate through the arraylist a number of ways. One way is the iterator:-

我想您可以通过多种方式遍历 arraylist。一种方法是迭代器:-

ArrayList<String> al = new ArrayList<String>();

al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");

System.out.print("Original contents of al: ");
Iterator<String> itr = al.iterator();
while (itr.hasNext()) {
  String element = itr.next();
  System.out.print(element + " ");
}

Another way would be a loop:

另一种方式是循环:

for(int i = 0; i < list.size(); i++){
    list[i].a = 29;
}

Hope this helps in any way.

希望这有任何帮助。

Ref

参考

http://www.tutorialspoint.com/java/java_using_iterator.htm

http://www.tutorialspoint.com/java/java_using_iterator.htm

http://examples.javacodegeeks.com/core-java/util/arraylist/arraylist-in-java-example-how-to-use-arraylist/

http://examples.javacodegeeks.com/core-java/util/arraylist/arraylist-in-java-example-how-to-use-arraylist/

UPDATE

更新

I thought that I should just put this out there from research due to the comment below about performance.

由于下面关于性能的评论,我认为我应该把它从研究中拿出来。

The Android docs

Android 文档

http://developer.android.com/training/articles/perf-tips.html

http://developer.android.com/training/articles/perf-tips.html

states:

状态:

The enhanced for loop (also sometimes known as "for-each" loop) can be used for collections >that implement the Iterable interface and for arrays. With collections, an iterator is >allocated to make interface calls to hasNext() and next(). With an ArrayList, a hand-written >counted loop is about 3x faster (with or without JIT), but for other collections the enhanced >for loop syntax will be exactly equivalent to explicit iterator usage.

There are several alternatives for iterating through an array:

增强的 for 循环(有时也称为“for-each”循环)可用于实现 Iterable 接口的集合和数组。对于集合,分配了一个迭代器来对 hasNext() 和 next() 进行接口调用。使用 ArrayList,手写 >counted 循环大约快 3 倍(有或没有 JIT),但对于其他集合,增强的 >for 循环语法将完全等同于显式迭代器的使用。

迭代数组有几种替代方法:

static class Foo {
    int mSplat;
}

Foo[] mArray = ...

public void zero() {
    int sum = 0;
    for (int i = 0; i < mArray.length; ++i) {
        sum += mArray[i].mSplat;
    }
}

public void one() {
    int sum = 0;
    Foo[] localArray = mArray;
    int len = localArray.length;

    for (int i = 0; i < len; ++i) {
        sum += localArray[i].mSplat;
    }
}

public void two() {
    int sum = 0;
    for (Foo a : mArray) {
        sum += a.mSplat;
    }
}
  • zero() is slowest, because the JIT can't yet optimize away the cost of getting the array length once for every iteration through the loop.

  • one() is faster. It pulls everything out into local variables, avoiding the lookups. Only the array length offers a performance benefit.

  • two() is fastest for devices without a JIT, and indistinguishable from one() for devices with a JIT. It uses the enhanced for loop syntax introduced in version 1.5 of the Java programming language.

  • zero() 是最慢的,因为 JIT 还不能优化循环每次迭代获取数组长度的成本。

  • () 更快。它将所有内容提取到局部变量中,避免查找。只有数组长度提供了性能优势。

  • 对于没有 JIT 的设备,two() 是最快的,对于有 JIT 的设备,与 one() 没有区别。它使用 Java 编程语言 1.5 版中引入的增强的 for 循环语法。

So, you should use the enhanced for loop by default, but consider a hand-written counted loop for performance-critical ArrayList iteration. Also this is stated by Josh Bloch's Effective Java, item 46.The iterator and the index variables are both just clutter. Furthermore, they represent opportunities for error.

因此,您应该默认使用增强的 for 循环,但考虑使用手写计数循环进行性能关键的 ArrayList 迭代。Josh Bloch 的 Effective Java 第 46 项也说明了这一点迭代器和索引变量都只是杂乱无章。此外,它们代表了出错的机会。

The preferred idiom for iterating over collections and arrays

迭代集合和数组的首选习惯用法

for(Element e : elements){
    doSomething(e);
}

Josh also states when you see the colon : read it as "In". The loop reads as for each element e in elements. I do not claim this work as my own even though I wish it was. If you want to learn more about efficient code then I suggest reading Josh Bloch's Effective Java.

当您看到冒号时,Josh 还会说:将其读作“In”。循环读取元素中的每个元素 e。即使我希望它是我自己的,我也不会声称这是我自己的。如果您想了解有关高效代码的更多信息,我建议您阅读 Josh Bloch 的 Effective Java。

回答by Víctor Albertos

Try the following:

请尝试以下操作:

class x {
    public int a;
    public String b;
}


private void test() {
    List<x> items = getList();
    for (x item: items) {
        System.out.print("val: " + item.a);
    }
}

private List<x> getList() {

    List<x> items = new ArrayList<x>();

    x oneObject = new x();
    oneObject.a = 1;
    oneObject.b = "val1";
    items.add(oneObject);


    x anotherObject = new x();
    anotherObject.a = 2;
    anotherObject.b = "val2";
    items.add(anotherObject);

    return items;
}