how to compare the Java Byte[] array?

后端 未结 15 2355
囚心锁ツ
囚心锁ツ 2020-12-13 01:17
public class ByteArr {

    public static void main(String[] args){
        Byte[] a = {(byte)0x03, (byte)0x00, (byte)0x00, (byte)0x00};
        Byte[] b = {(byte)0x         


        
相关标签:
15条回答
  • 2020-12-13 01:43

    Cause they're not equal, ie: they're different arrays with equal elements inside.

    Try using Arrays.equals() or Arrays.deepEquals().

    0 讨论(0)
  • 2020-12-13 01:45

    Try for this:

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

    I am also not sure about this, but try this may be it works.

    0 讨论(0)
  • 2020-12-13 01:48

    I looked for an array wrapper which makes it comparable to use with guava TreeRangeMap. The class doesn't accept comparator.

    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.

    .

    0 讨论(0)
  • 2020-12-13 01:49

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

    0 讨论(0)
  • 2020-12-13 01:49

    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;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-13 01:51

    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.

    0 讨论(0)
提交回复
热议问题