Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop thorough a 2D ArrayList in Java and fill it?

I am trying to use 2D arrayLists in Java. I have the definition:

ArrayList<ArrayList<Integer>> myList = new ArrayList<ArrayList<Integer>>();

How can I loop through it and enter in numbers starting from 1? I know that I can access a specific index by using:

myList.get(i).get(j)

Which will get the value. But how do I add to the Matrix?

Thanks

like image 600
user2955610 Avatar asked May 27 '26 18:05

user2955610


1 Answers

You can use a nested for loop. The i-loop loops through the outer ArrayList and the j-loop loops through each individual ArrayList contained by myList

for (int i = 0; i < myList.size(); i++)
{
    for (int j = 0; j < myList.get(i).size(); j++)
    {
        // do stuff
    } 
}

Edit: you then fill it by replacing // do stuff with

myList.get(i).add(new Integer(YOUR_VALUE)); // append YOUR_VALUE to end of list

A Note: If the myList is initially unfilled, looping using .size() will not work as you cannot use .get(SOME_INDEX) on an ArrayList containing no indices. You will need to loop from 0 to the number of values you wish to add, create a new list within the first loop, use .add(YOUR_VALUE) to append a new value on each iteration to this new list and then add this new list to myList. See Ken's answer for a perfect example.

like image 174
bpgeck Avatar answered May 30 '26 07:05

bpgeck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!