Mina Gabriel
Mina Gabriel

Reputation: 25180

iterate through ArrayList<T> java?

I'm learning Android and Java i have created a class let's say like this

 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

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

Upvotes: 5

Views: 32981

Answers (4)

Mark
Mark

Reputation: 491

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

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://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

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:

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.

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.

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.

Upvotes: 3

V&#237;ctor Albertos
V&#237;ctor Albertos

Reputation: 8303

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;
}

Upvotes: 0

Caleb Brinkman
Caleb Brinkman

Reputation: 2529

There are two ways to do this:

  1. A for loop
  2. Using the iterator method.

for loop:

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(ObjectType variableName : InCollection)

You could also use a standard for loop:

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)

iterator method:

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

Upvotes: 23

wmora
wmora

Reputation: 1203

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

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

Upvotes: 3

Related Questions