Skip to main content

Setting up 2D ArrayList

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
1 reply [Last post]
zscipio
Offline
Joined: 2008-11-08
Points: 0

My background is over 50 years of programming 3rd generation languages so much of what I code is colored by that experience. Now I am coding java & many thing I don't understand. Can someone help me to understand the following problem.

I need a 2-d array, array, of !0 rows by 4 columns. The member of the array are booleans & I need to be able to set array(row, column) to TRUE or FALSE

Case 1:
In Java define a 2-D array:
<code>
private ArrayList<ArrayList<Boolean>> twoDArray = new ArrayList<ArrayList<Boolean>>(10);
</code>
Next define an array of booleans and initialize 4 elements to false:
<code>
ArrayList<Boolean> rowOfBooleans new ArrayList<Boolean>(4);
rowOfBooleans.add(false);
rowOfBooleans.add(false);
rowOfBooleans.add(false);
rowOfBooleans.add(false);
</code>

Finally set up 10 rows of 4 columns of booleans:
<code>
for (int row = 0; row < 10; row++)
{
twoDArray.add(rowOfBooleans);
}
</code>

To set an element at (2,3) to true
<code>
twoDArray.get(2).set(3, true);
</code>

But what happens is every row's column 3 is set to true;

In order to get the array set to work properly the construction of the rowOFBooleans must be put inside the 'for loop'.

Case 2:
<code>
ArrayList<Boolean> rowOfBooleans;
for (int row = 0; row < 10; row++)
{
rowOfBooleans = new ArrayList<Boolean>(4);
rowOfBooleans.add(false);
rowOfBooleans.add(false);
rowOfBooleans.add(false);
rowOfBooleans.add(false);
twoDArray.add(rowOfBooleans);
}
</code>

My surmise is that in the first case Java doesn't store the values of rowOfBooleans in the twoDArray but rather stores a pointer to the ArrayList rowOfBooleans. Thus when ever an element is changed each row is pointing to the same rowOfBooleans.

In the second case each row is pointing to a different rowOfBooleans.

Can anyone help me understand what is happening?

Thank you.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
tianwang
Offline
Joined: 2008-06-07
Points: 0

FIrstly, since you already know the dimensions of your 2d array, you should not use ArrayList<ArrayList<Boolean>> as your data structure.
You could simply use a boolean[10][4] to solve your requirements.
But back to your issue,
'My surmise is that in the first case Java doesn't store the values of rowOfBooleans in the twoDArray but rather stores a pointer to the ArrayList rowOfBooleans. Thus when ever an element is changed each row is pointing to the same rowOfBooleans.' is what is happening.
Java doesnt know that you want to clone a separate copy of the array list when you call twoDArray.add(rowOfBooleans)
It is plausible that someone else would have wanted that effect instead of what you wanted.