0

I've got an Array in an ArrayList, and I want to access each element in the Array individually to use them. My code doesn't work:

ArrayList<int[]> freeSpot = new ArrayList<int[]>();

    for (int x = 0; x < 3; x++) {
        for (int y = 0; y < 3; y++) {
            freeSpot.add(new int[]{x, y});
        }
    }

    System.out.println(freeSpot.get(int[0]));

Hope somebody can help! Thanks.

3
  • Did you mean freeSpot.get(0)? Commented Nov 30, 2016 at 20:17
  • System.out.println(Arrays.toString(freeSpot.get(0))); Commented Nov 30, 2016 at 20:18
  • System.out.println(freeSpot.get(0)[0]); Commented Nov 30, 2016 at 20:19

2 Answers 2

1

Slightly different approach:

List<Integer[]> freeSpot = new ArrayList<>();

for (int x = 0; x < 3; x++) {
    for (int y = 0; y < 3; y++) {
        freeSpot.add(new Integer[]{x, y});
    }
}

for(Integer[] entry : freeSpot) {
    System.out.println("x: " + entry[0] + " y: " + entry[1]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You should do the following:

 System.out.println(freeSpot.get(x)[y]);

where x if the index of the List and y the index of the array.

For example:

to get the first element of the array of the first element of the list :

System.out.println(freeSpot.get(0)[0]);

to get the second element of the array of the first element of the list :

 System.out.println(freeSpot.get(0)[1]);

2 Comments

get(0)[1] and get(0)[2] should be get(0)[0] and get(0)[1]
I can't edit yet. lol I am also guilty of the same type of mistakes.

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.