1

I tried the following program but it doesn't print what it should. I'm sure that the way I check the array is correct but when I put it in a "if" tester the program doesn't give me results

import java.util.Arrays;

public class 3Dmatrix {
  public static void main(String[] args) {
    int [][][] cube;
    cube = new int [2][2][2];
    cube [0][0][0] = 4;
    cube [0][0][1] = 2;
    if (cube [0] [0] == new int[]{4, 2}) {
        System.out.println("cat");
    }
  }
}
Manu
  • 1,474
  • 1
  • 12
  • 18
  • Possible duplicate of [Java: How to test on array equality?](http://stackoverflow.com/questions/8051084/java-how-to-test-on-array-equality) – Manu Dec 10 '15 at 14:22
  • 1
    Short answer: use `Arrays.deepEquals()` – Manu Dec 10 '15 at 14:23

1 Answers1

1

Use the Arrays.equals method. Here you go, this works and returns True:

import java.util.Arrays;
public class scratch
{

    public static void main(String[] args)
    {
        int[][][] cube;
        cube = new int[2][2][2];
        cube[0][0][0] = 4;
        cube[0][0][1] = 2;
        int[] test = new int[]{4, 2};
        for (int i = 0; i < test.length; i++)
            System.out.println(cube[0][0][i] + " " + test[i]); //Printing test
        if (Arrays.equals(cube[0][0], new int[]{4, 2})) //Returns true
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}



Output: http://ideone.com/l2q7i6

gabbar0x
  • 4,046
  • 5
  • 31
  • 51