Why does == not work with byte arrays in Java?
For example:
byte[] a = new byte[]{1,2,3,4};
byte[] b = new byte[]{1,2,3,4};
a == b //false
a.equals(b) //false
Arrays.equals(a,b) //true
Why does == not work with byte arrays in Java?
For example:
byte[] a = new byte[]{1,2,3,4};
byte[] b = new byte[]{1,2,3,4};
a == b //false
a.equals(b) //false
Arrays.equals(a,b) //true
== and byte[] realization of equals uses links comparison. In this case links point to different regions in memory. If you follow to source code for equals realization for byte[], you'll see the following:
public boolean equals(Object obj) {
return (this == obj);
}
This actually the default implementation from Object
Arrays.equals(a,b) uses comparison of the contents of arrays.
Also, see the following What is the difference between == vs equals() in Java?
In java, array is treated like an object. So == will compare only the references. Also a.equals(b) is same as a==b as default implementation in Object class check the reference only.
If you really wish to compare the content, you should use Arrays.equals(a,b). Though this will not work in multidimensional array.
If you do something like below, it will result true, as both will refer the same reference.
b = a;
System.out.println(a==b);
As simple as equals compare if they share same memory region, and Arrays.equals compares the content of array.
variable a and b are in different memory locations. if you print the a and b it will print with different hash codes.
hence a == b and a.equals(b) gives false
In the java source code equals method code is as the following
public boolean equals(Object obj) {
return (this == obj);
}
So equals is just like the == that you are testing. If you want to get a meaning full answer using equals method you have to override it by yourself.
and the Arrays.equals method is as the following.
public static boolean equals(byte[] a, byte[] a2) {
if (a==a2)
return true;
if (a==null || a2==null)
return false;
int length = a.length;
if (a2.length != length)
return false;
for (int i=0; i<length; i++)
if (a[i] != a2[i])
return false;
return true;
}
a.equals(b) just use Object.equals()(byte[] is a Object and donot override the method equals()), see the source:
public boolean equals(Object obj) {
return (this == obj);
}
== compares reference's address.(not consider special type: String,int etc.)
Arrays.equals() compares reference's address and content, see the source:
public static boolean equals(byte[] a, byte[] a2) {
if (a==a2)
return true;
if (a==null || a2==null)
return false;
int length = a.length;
if (a2.length != length)
return false;
for (int i=0; i<length; i++)
if (a[i] != a2[i])
return false;
return true;
}