how to compare the Java Byte[] array?

后端 未结 15 2359
囚心锁ツ
囚心锁ツ 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: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  SortedMap newByteArrayMap() {
            return new TreeMap<>(new ByteArrayComparator());
        }
    
        public static SortedSet newByteArraySet() {
            return new TreeSet<>(new ByteArrayComparator());
        }
    
        static class ByteArrayComparator implements Comparator {
            @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;
            }
        }
    }
    

提交回复
热议问题