Java Map <>可能具有内向类型吗?

mil*_*lan 0 java hashmap

这怎么可能: HashMap<byte[], byte[]>什么是byte []的hash()?

Joa*_*uer 12

是的,这是可能的(有一个很大的警告,见下文),但byte[]不是"内在类型".首先,没有这样的东西,你可能意味着"原始类型".二:byte[]不是基本类型,byte是.数组始终是引用类型.

数组没有特定的hashCode实现,因此它们只使用hashCodeofObject,这意味着hashCode将是indentity-hashCode,它独立于实际内容.

换句话说:a byte[]是一个非常糟糕的Map密钥,因为您只能使用完全相同的实例检索该值.

如果您需要hashCode()基于数组的基于内容的内容,您可以使用Arrays.hashCode(),但这对您(直接)不会有帮助Map.还要Arrays.equals()检查内容是否相等.

可以换你byte[]在实现薄包装对象hashCode()equals()(使用上面提到的方法):

import java.util.Arrays;

public final class ArrayWrapper {
  private final byte[] data;
  private final int hash;

  public ArrayWrapper(final byte[] data) {
    // strictly speaking we should make a defensive copy here,
    // but I *assume* (and should document) that the argument
    // passed in here should not be changed
    this.data = data;
    this.hash = Arrays.hashCode(data);
  }

  @Override
  public int hashCode() {
    return hash
  }

  @Override
  public boolean equals(Object o) {
    if (!(o instanceof ArrayWrapper)) {
      return false;
    }
    ArrayWrapper other = (ArrayWrapper) o;
    return this.hash == other.hash && Arrays.equals(this.data, other.data);
  }
  // don't add getData to prevent having to do a defensive copy of data
}
Run Code Online (Sandbox Code Playgroud)

使用此类,您可以使用Map<ArrayWrapper,byte[]>.