Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Filling multidimensional (2d) ArrayList like a 2d array

A while ago before I got used to object object oriented programming I created a basic TicTacToe game and to create the board I used an array.

The code is a complete mess because I didn't properly understand how to use objects, but I did initialize the board correctly:

char[][] board = new char[3][3];
for (int i = 0; i < board.length; i++){
    for (int j = 0; j < board[i].length; j++){
        board[i][j] = '[]' //or something like that...don't remember exactly
    }
}

My question is how would you this with an ArrayList?

     ArrayList <ArrayList<Character>> board = new ArrayList(); // this initialization is not
    // wrong using Java 8 but for earlier versions you would need to state the type on both 
//sides of the equal sign not just the left
        for (int i = 0; i < board.size(); i++){
                for (int j = 0; j < board.get(i).size(); j++){
                    board.get(i).get(j).add('[]');
                }
            }

but that does not work.

It does not have to be exactly like this, I just generally want to understand how to handle multidimensional ArrayLists.

-thanks

like image 954
Cornelius Avatar asked Oct 15 '25 15:10

Cornelius


2 Answers

Unlike arrays, you can't initialize an entire ArrayList directly. You can specify the expected size beforehand (this helps performance when you are using very large lists, so it is a good practice to do it always).

int boardSize = 3;
ArrayList<ArrayList<Character>> board = new ArrayList<ArrayList<Character>>(boardSize);
for (int i = 0; i < boardSize; i++) {
    board.add(new ArrayList<Character>(boardSize));
    for (int j = 0; j < boardSize; j++){
        board.get(i).add('0');
    }
}
like image 163
Glorfindel Avatar answered Oct 18 '25 08:10

Glorfindel


The main difference is that in your original code you had a multi-dimensional array of primitives (in this case, char) and all you had to do was assign a new primitive value to each slot in the array.

However what you want now is an ArrayList of (ArrayList of Character). When you create the ArrayList it is empty. In order to procede you are going to need to fill it with several (ArrayList of Character) before you can begin to start adding Characters themselves.

So for example,

ArrayList <ArrayList<Character>> board = new ArrayList<>();

for (int i=0; i<3; i++) {
  board.add(new ArrayList<Character>());
}

Now you can start adding Characters to your lists:

for (int i=0; i<3; i++) {
  for (int j=0; j<3; j++) {
    board.get(i).add('A');
  }
}

Hope this helps.

like image 21
Julian Wright Avatar answered Oct 18 '25 07:10

Julian Wright



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!