developer tip

Java Byte [] 배열을 비교하는 방법은 무엇입니까?

optionbox 2020. 10. 7. 07:35
반응형

Java Byte [] 배열을 비교하는 방법은 무엇입니까?


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));
    }
}

나는 그들 모두가 왜 거짓으로 인쇄하는지 모르겠습니다.

"java ByteArray"를 실행하면 대답은 "false false false false"입니다.

나는 a []가 b []와 같다고 생각하지만 JVM은 내가 틀렸다고 말하고 있는데, 왜 ??


Arrays.equals()기본 유형 값 (예 : 바이트)을 포함하는 배열의 실제 내용을 비교하려는 경우 사용하십시오 .

System.out.println(Arrays.equals(aa, bb));

Arrays.deepEquals객체를 포함하는 배열의 비교에 사용 합니다.


왜냐하면 그것들이 같지 않기 때문입니다. 즉, 내부에 동일한 요소를 가진 다른 배열입니다.

Arrays.equals()또는을 사용해보십시오 Arrays.deepEquals().


byte []는 변경 가능하므로 .equals()동일한 객체 인 경우 에만 처리됩니다 .

사용해야 할 내용을 비교하고 싶다면 Arrays.equals(a, b)

BTW : 제가 디자인하는 방식이 아닙니다. ;)


봤어 Arrays.equals()?

편집 : 귀하의 의견에 따라 문제가 바이트 배열을 HashMap 키로 사용하는 경우이 질문 을 참조하십시오 .


배열을 일반 HashMap 키로 사용하려는 경우 작동하지 않습니다. 배열을 보유하고 equals(...)hashcode(...)메소드가 java.util.Arrays 메소드의 결과를 리턴 하는 사용자 정의 랩퍼 오브젝트를 작성하는 것을 고려하십시오 . 예를 들면 ...

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;
   }


}

이 래퍼 클래스의 개체는 키로 잘 작동 HashMap<MyByteArray, OtherType>하며 equals(...)hashCode(...)메서드 를 깔끔하게 사용할 수 있습니다.


값 평등이 아닌 객체 ID를 테스트하기 때문에 거짓을 반환합니다. 배열이 실제로 메모리에서 다른 객체이기 때문에 false를 반환합니다.

값이 같은지 테스트하려면 java.util.Arrays 의 편리한 비교 함수를 사용해야합니다.

예 :

import java.util.Arrays;

'''''

Arrays.equals(a,b);

Apache DirectoryByteArrayComparator 에서를 사용할 수도 있습니다 . 같음 외에도 한 배열이 다른 배열 보다 큰지 비교할 수 있습니다 .


이것을 시도하십시오 :

boolean blnResult = Arrays.equals(byteArray1, byteArray2);

나는 또한 이것에 대해 확신하지 못하지만 이것이 효과가있을 수 있습니다.


왜 a []가 b []와 같지 않습니까? 때문에 equals함수가 실제로 호출 Byte[]또는 byte[]이다 Object.equals(Object obj). 이 함수는 객체 식별 만 비교하고 배열의 내용을 비교하지 않습니다.


구아바 TreeRangeMap과 함께 사용할 수있는 배열 래퍼를 찾았습니다. 클래스는 비교기를 허용하지 않습니다.

After some research I realized that ByteBuffer from JDK has this feature and it doesn't copy original array which is good. More over you can compare faster with ByteBuffer::asLongBuffer 8 bytes at time (also doesn't copy). By default ByteBuffer::wrap(byte[]) use BigEndian so order relation is the same as comparing individual bytes.

.


Java byte compare,

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;
    }

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().


You can also use org.apache.commons.lang.ArrayUtils.isEquals()


Arrays.equals is not enough for a comparator, you can not check the map contain the data. I copy the code from Arrays.equals, modified to build a Comparator.

class ByteArrays{
    public static <T> SortedMap<byte[], T> newByteArrayMap() {
        return new TreeMap<>(new ByteArrayComparator());
    }

    public static SortedSet<byte[]> newByteArraySet() {
        return new TreeSet<>(new ByteArrayComparator());
    }

    static class ByteArrayComparator implements Comparator<byte[]> {
        @Override
        public int compare(byte[] a, byte[] b) {
            if (a == b) {
                return 0;
            }
            if (a == null || b == null) {
                throw new NullPointerException();
            }

            int length = a.length;
            int cmp;
            if ((cmp = Integer.compare(length, b.length)) != 0) {
                return cmp;
            }

            for (int i = 0; i < length; i++) {
                if ((cmp = Byte.compare(a[i], b[i])) != 0) {
                    return cmp;
                }
            }

            return 0;
        }
    }
}

There's a faster way to do that:

Arrays.hashCode(arr1) == Arrays.hashCode(arr2)

참고URL : https://stackoverflow.com/questions/9499560/how-to-compare-the-java-byte-array

반응형