5

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

Mina Gabriel
  • 23,150
  • 26
  • 96
  • 124
  • 3
    http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html – jmj Aug 27 '14 at 23:29
  • @JigarJoshi for(X myx : GetList) that was outstanding Thanks ... – Mina Gabriel Aug 27 '14 at 23:42
  • This question appears to be off-topic because it is about the very basics of a language – njzk2 Aug 28 '14 at 19:33
  • 1
    I seriously doubt that you could not find an answer to that question with a minimal search – njzk2 Aug 28 '14 at 19:33
  • @njzk2 i found some examples that uses Iterator but they were really complicated though – Mina Gabriel Aug 28 '14 at 20:03
  • http://stackoverflow.com/questions/6700717/how-to-iterate-through-an-array-list-arrayindexoutofboundsexception is the first link when searching `iterate arraylist java` in your favorite search engine... – njzk2 Aug 29 '14 at 01:08

4 Answers4

23

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
}
Caleb Brinkman
  • 2,489
  • 3
  • 26
  • 40
3

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

for (x item: GetList()) {
    doSomethingWithEachValue(item);
}
wmora
  • 1,203
  • 1
  • 9
  • 17
3

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.

Community
  • 1
  • 1
Mark
  • 491
  • 4
  • 7
  • Nice answer! Welcome to SO. – Vality Aug 27 '14 at 23:49
  • i'm new to java and from the link in the comment looks like iterate is not the best way of doing this type of task? – Mina Gabriel Aug 27 '14 at 23:50
  • http://developer.android.com/training/articles/perf-tips.html States there are two basic rules for writing efficient code: Don't do work that you don't need to do. Don't allocate memory if you can avoid it. However at the end of the day your the programmer. Do whichever you feel your comfortable at. @MinaGabriel – Mark Aug 27 '14 at 23:56
  • `Don't do work that you don't need to do` such as creating an iterator to loop on a List, you mean? – njzk2 Aug 28 '14 at 19:35
  • The link I gave 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. Again I just think it depends, but for this situation yes. If you think otherwise, it will be interesting to know your experience. @njzk2 – Mark Aug 28 '14 at 20:56
  • I usually don't care about that kind of performance until I need to. Having clean code and avoid indices where it is not absolutely necessary is better imho. The fast enum syntax is better at carrying the notion of `for each item` than the indexed syntax. – njzk2 Aug 29 '14 at 01:07
0

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;
}
Víctor Albertos
  • 8,093
  • 5
  • 43
  • 71