Compare two Byte Arrays? (Java)
Check out the static java.util.Arrays.equals()
family of methods. There's one that does exactly what you want.
In your example, you have:
if (new BigInteger("1111000011110001", 2).toByteArray() == array)
When dealing with objects, ==
in java compares reference values. You're checking to see if the reference to the array returned by toByteArray()
is the same as the reference held in array
, which of course can never be true. In addition, array classes don't override .equals()
so the behavior is that of Object.equals()
which also only compares the reference values.
To compare the contents of two arrays, static array comparison methods are provided by the Arrays class
byte[] array = new BigInteger("1111000011110001", 2).toByteArray();
byte[] secondArray = new BigInteger("1111000011110001", 2).toByteArray();
if (Arrays.equals(array, secondArray))
{
System.out.println("Yup, they're the same!");
}
Java doesn't overload operators, so you'll usually need a method for non-basic types. Try the Arrays.equals() method.