1

What is the simplest way to just iterate over ArrayList rows values?

For example I have two ArrayList:

ArrayList<Object> main = new ArrayList<Object>();
ArrayList<Object> row = new ArrayList<Object>();

I use two fors to add values into main. First I add row, then when row iterations end, I add it to main, and then repeat for another row etc. For example:

for(int i=0; i < somearray.length; i++){
  for(int j=0; j < somearray2.length; j++){
    if(somearray2[j] == true)
      row.add(somearray2[j]);
    }
  main.add(row);

}

So now I get ArrayList filled with rows like I need. But later I need to iterate over rows values, not just rows themselves from main ArrayList. How can I do that? As I only see the method:

main.get(index), which let's me get a row, but nothing more.

2 Answers 2

7

So, based on your description, main is not a list of Objects, but a list of lists. So it should be declared as

List<List<Object>> main = new ArrayList<>();

The iteration now becomes obvious:

for (List<Object> row : main) {
    for (Object element : row) {
        // do what you want here
    }
}

This has the additional advantage of making your code type-safe: you won't be able to add, inadvertently, anything other than a List<Object> inside the main list.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes then access them as: ((ArrayList<Object>)main.get(index)).get(index2);. But if you want all of your row element to be added to main array, you can make use of:

Collections.addAll(main, row.toArray());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.