Jeggy
Jeggy

Reputation: 1650

compare 2 2Dimensional arrays - Java

Why isn't this true?

int[][] arrayOfSets = {{1,2},{9,10},{1,2},{3,5}};
int[][] test =        {{1,2},{9,10},{1,2},{3,5}};

if(arrayOfSets==test){ //{{1,2},{9,10},{1,2},{3,5}}){
   System.out.println("Exactly the same");
}

The output should be "Exactly the same". or how can I compare 2 variables with 2dimensional arrays?

Upvotes: 0

Views: 272

Answers (3)

thisismario123
thisismario123

Reputation: 43

To compare multidimensional arrays, use .deepEquals The link explains why

.deepEquals

And the following link explains why == or .equals doesn't work.

.equals definition

Upvotes: 2

FatherMathew
FatherMathew

Reputation: 990

This does not work because == compares the reference ie you can think of that as memory address..In this case since you are declaring 2 different arrays, their addresses are bound to be different.

One small suggestion since your array doesn't contain consecutive numbers such as {1,2}, {1,3} similarly.... you can instead use objects with 2 instance numbers and put those objects inside an array

Upvotes: 0

Fevly Pallar
Fevly Pallar

Reputation: 3109

You use == thats why failed, it's for identical of object check so use :

boolean check = Arrays.deepEquals(arrayOfSets, test);

Upvotes: 1

Related Questions