Search code examples
javaarraysarraylistchess

Passing array as parameter in a method


I am trying to make a simple Chess program in java. There is an ArrayList that stores all the moves the knight can do, with each move being an Integer[]. The first item in the array is the row, and the second is the column. It looks like this:

ArrayList<Integer[]> moves = new ArrayList<>();
moves.add({row - 2, col - 1});
moves.add({row - 1, col - 2});
moves.add({row - 2, col + 1});
moves.add({row - 1, col + 2});
moves.add({row + 1, col - 2});
moves.add({row + 2, col - 1});
moves.add({row + 2, col + 1});
moves.add({row + 1, col + 2});

For some reason, when I try to run the code, I get around 100 errors including illegal start of expression, <identifier> expected, and not a statement.

I'm not sure what's causing the problem. Does Java not allow storing arrays in ArrayLists, or is there something wrong with the particular syntax?


Solution

  • You always need to initialize the array for this to work.

    ArrayList<Integer[]> moves = new ArrayList<>();
    moves.add(new Integer[]{ 2, 1});