Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compare the Java Byte[] array?

Tags:

java

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??

like image 969
Lazy Avatar asked Feb 29 '12 12:02

Lazy


People also ask

What does byte [] do in Java?

A byte in Java is 8 bits. It is a primitive data type, meaning it comes packaged with Java. Bytes can hold values from -128 to 127. No special tasks are needed to use it; simply declare a byte variable and you are off to the races.

How do you determine if a byte array is equal?

equals(byte[] a, byte[] a2) method returns true if the two specified arrays of bytes are equal to one another. Two arrays are equal if they contain the same elements in the same order.

Can you compare byte and int in Java?

In java automatic type conversion converts any small data type to the larger of the two types. So byte b is converted to int b when you are comparing it with int a . Do know that double is the largest data type while byte is the smallest.


1 Answers

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.

like image 58
Lukasz Avatar answered Sep 19 '22 06:09

Lukasz