-1

I am trying to compare two arrays.

I initialise them:

public static int [][] craftarray = {{0,0,0},{0,0,0},{0,0,0}};
public static int [][] stone = {{0,0,0},{0,0,0},{0,0,0}};

When i tried to compare them using:

Inventory.craftarray.equals(Craft.stone)

It did not say they were equal so i printed out the arrays.

the craft array came back with 0's while stone returned ' [[I@44ffb2 '.

Why is this happening?

thmas
  • 142
  • 12

1 Answers1

5

Instead use, Arrays.deepEquals(Object[] a, Object[] b). That will compare element by element using the Object.equals() method, recursively if it encounters a new array.

The reason why your code doesn't work, is because there is no special implementation for equals() for arrays. So, two different arrays with the same content won't result in true when calling equals.

Basically, this is solved by using Arrays.equals(). This will compare by using equals on each object of the array. But since you are using an arrays of arrays, you will face the same problem again. That is where Arrays.deepEquals() comes in.


Context aware comment: note that the Minecraft-style crafting doesn't require the pattern to be at a specific location. For example, a torch (a stick with coal on top), can be crafted at 6 different locations on the crafting table. This means that deepEquals() is not going to help. I suggest you write your own method with some intelligent algorithm to do the job. Here (on github) is an old project of mine, where I did the same trick. Take a look at the equalsRecipe() method I wrote.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287