您认为使用字节数组作为Map key有什么问题吗?我也可以通过String来做new String(byte[])和哈希,但是使用byte[]会更简单。
发布于 2012-12-30 08:32:15
为此,我们可以使用ByteBuffer (这基本上是带有比较器的byte[]包装器)
HashMap<ByteBuffer, byte[]> kvs = new HashMap<ByteBuffer, byte[]>();
byte[] k1 = new byte[]{1,2 ,3};
byte[] k2 = new byte[]{1,2 ,3};
byte[] val = new byte[]{12,23,43,4};
kvs.put(ByteBuffer.wrap(k1), val);
System.out.println(kvs.containsKey(ByteBuffer.wrap(k2)));将打印
true发布于 2011-11-12 08:11:52
您可以使用java.math.BigInteger。它有一个BigInteger(byte[] val)构造函数。它是一个引用类型,因此可以用作哈希表的键。.equals()和.hashCode()分别定义为整数,这意味着BigInteger与byte[]数组具有一致的等于语义。
发布于 2016-07-24 21:44:08
我非常惊讶的是,答案没有指出最简单的替代方案。
是的,使用HashMap是不可能的,但是没有人阻止您使用SortedMap作为替代。唯一需要做的就是编写一个比较器,它需要比较数组。它的性能不如HashMap,但如果你想要一个简单的替代方案,你可以这样做(如果你想隐藏实现,你可以用SortedMap代替Map ):
private SortedMap<int[], String> testMap = new TreeMap<>(new ArrayComparator());
private class ArrayComparator implements Comparator<int[]> {
@Override
public int compare(int[] o1, int[] o2) {
int result = 0;
int maxLength = Math.max(o1.length, o2.length);
for (int index = 0; index < maxLength; index++) {
int o1Value = index < o1.length ? o1[index] : 0;
int o2Value = index < o2.length ? o2[index] : 0;
int cmp = Integer.compare(o1Value, o2Value);
if (cmp != 0) {
result = cmp;
break;
}
}
return result;
}
}此实现可以针对其他数组进行调整,您必须知道的唯一一件事是相等的数组(=具有相等成员的相等长度)必须返回0,并且您有一个确定的顺序
https://stackoverflow.com/questions/1058149
复制相似问题