Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through ArrayList of objects?

Tags:

java

arraylist

I have a class called SparseMatrix. It contains an ArrayList of Nodes (also class). I am wondering of how to iterate through the Array and access a value in Node. I have tried the following:

 //Assume that the member variables in SparseMatrix and Node are fully defined.
 class SparseMatrix {
     ArrayList filled_data_ = new ArrayList();
     //Constructor, setter (both work)

     // The problem is that I seem to not be allowed to use the operator[] on
     // this type of array.
     int get (int row, int column) {
         for (int i = 0; i < filled_data_.size(); i++){
             if (row * max_row + column == filled_data[i].getLocation()) {
                 return filled_data[i].getSize();
             }
         }
         return defualt_value_;
     }
 }

I will probably switch to static arrays (and remake it every time I add an object). If anyone has a solution, I would very much appreciate you sharing it with me. Also, thank you in advance for helping me.

Feel free to ask questions if you don't understand anything here.

like image 286
sudomeacat Avatar asked Oct 08 '16 04:10

sudomeacat


Video Answer


1 Answers

Assuming filled_data_ is a list that contains list of objects of a class named Node.

List<Nodes> filled_data_ = new ArrayList<>();
for (Node data : filled_data_) {
    data.getVariable1();
    data.getVariable2();
}

More info http://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/

like image 60
HARDI Avatar answered Oct 04 '22 16:10

HARDI