how to compare the Java Byte[] array?

后端 未结 15 2372
囚心锁ツ
囚心锁ツ 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:57

    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 and will allow for clean use of equals(...) and hashCode(...) methods.

提交回复
热议问题