how to compare the Java Byte[] array?
public class ByteArr {
public static void main(String[] args){
Byte[] a = {(byte)0x03, (byte)0x00, (byte)0x00, (byte)0x00};
Byte[] b = {(byte)0x03, (byte)0x00, (byte)0x00, (byte)0x00};
byte[] aa = {(byte)0x03, (byte)0x00, (byte)0x00, (byte)0x00};
byte[] bb = {(byte)0x03, (byte)0x00, (byte)0x00, (byte)0x00};
System.out.println(a);
System.out.println(b);
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(aa);
System.out.println(bb);
System.out.println(aa == bb);
System.out.println(aa.equals(bb));
}
}
I do not know why all of them print false.
When I run "java ByteArray", the answer is "false false false false".
I think the a[] equals b[] but the JVM is telling me I am wrong, why??
Solution 1:
Use Arrays.equals()
if you want to compare the actual content of arrays that contain primitive types values (like byte).
System.out.println(Arrays.equals(aa, bb));
Use Arrays.deepEquals
for comparison of arrays that contain objects.
Solution 2:
Cause they're not equal, ie: they're different arrays with equal elements inside.
Try using Arrays.equals()
or Arrays.deepEquals()
.
Solution 3:
As byte[] is mutable it is treated as only being .equals()
if its the same object.
If you want to compare the contents you have to use Arrays.equals(a, b)
BTW: Its not the way I would design it. ;)
Solution 4:
have you looked at Arrays.equals()
?
Edit: if, as per your comment, the issue is using a byte array as a HashMap key then see this question.