Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate through ArrayList<T> java?

Tags:

java

android

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

like image 946
Mina Gabriel Avatar asked Nov 28 '22 16:11

Mina Gabriel


1 Answers

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
}
like image 76
Caleb Brinkman Avatar answered Dec 13 '22 05:12

Caleb Brinkman