public class ByteArr {
public static void main(String[] args){
Byte[] a = {(byte)0x03, (byte)0x00, (byte)0x00, (byte)0x00};
Byte[] b = {(byte)0x
Because neither ==
nor the equals()
method of the array compare the contents; both only evaluate object identity (==
always does, and equals()
is not overwritten, so the version from Object
is being used).
For comparing the contents, use Arrays.equals().
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.
If you're trying to use the array as a generic HashMap key, that's not going to work. Consider creating a custom wrapper object that holds the array, and whose equals(...)
and hashcode(...)
method returns the results from the java.util.Arrays methods. For example...
import java.util.Arrays;
public class MyByteArray {
private byte[] data;
// ... constructors, getters methods, setter methods, etc...
@Override
public int hashCode() {
return Arrays.hashCode(data);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyByteArray other = (MyByteArray) obj;
if (!Arrays.equals(data, other.data))
return false;
return true;
}
}
Objects of this wrapper class will work fine as a key for your HashMap<MyByteArray, OtherType>
and will allow for clean use of equals(...)
and hashCode(...)
methods.
You can also use a ByteArrayComparator
from Apache Directory. In addition to equals it lets you compare if one array is greater than the other.
They are returning false because you are testing for object identity rather than value equality. This returns false because your arrays are actually different objects in memory.
If you want to test for value equality should use the handy comparison functions in java.util.Arrays
e.g.
import java.util.Arrays;
'''''
Arrays.equals(a,b);
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. ;)