DiG*_*GMi 4 java arrays hashcode
出于某种原因,Arrays.deepHashCode()无法使用byte[].
还有其他等价物吗?
首先,不需要"深度".这是一个原始的.你不需要Deep.
只是用 Arrays.hashCode(byte[] yourArray)
编辑:为了澄清,Deep意味着深入研究数组中包含的对象.鉴于您正在处理基元,您只需在计算中使用原始值本身.这就是为什么Deep方法都不围绕基元的原因.
接受的答案是正确的:使用Arrays.hashCode为byte []提供具有相同值的相同结果. 如果您有嵌套(深层)结构,则必须使用Arrays.deepHashCode.
import java.util.Arrays;
public class A {
public static void main(String[] args) {
byte[] a = {10, 32, -43, 80};
byte[] b = {13, -40};
byte[] c = {10, 32, -43, 80};
System.out.println("NOTE: A and C have identical values, B differs");
System.out.println("Using byte[].hashCode(): A and C have different hash codes");
System.out.println("a = " + a.hashCode());
System.out.println("b = " + b.hashCode());
System.out.println("c = " + c.hashCode());
System.out.println("Using Arrays.hashCode(): A and C have identical hash codes");
System.out.println("a = " + Arrays.hashCode(a));
System.out.println("b = " + Arrays.hashCode(b));
System.out.println("c = " + Arrays.hashCode(c));
System.out.println("Using Arrays.deepHashCode(): A and C have identical hash codes");
System.out.println("a = " + Arrays.deepHashCode(new Object[]{a}));
System.out.println("b = " + Arrays.deepHashCode(new Object[]{b}));
System.out.println("c = " + Arrays.deepHashCode(new Object[]{c}));
}
}
Run Code Online (Sandbox Code Playgroud)
这导致输出:
NOTE: A and C have identical values, B differs
Using byte[].hashCode(): A and C have different hash codes
a = 141847843
b = 329849131
c = 1119051810
Using Arrays.hashCode(): A and C have identical hash codes
a = 1250930
b = 1324
c = 1250930
Using Arrays.deepHashCode(): A and C have identical hash codes
a = 1250961
b = 1355
c = 1250961
Run Code Online (Sandbox Code Playgroud)
这是一个需要Arrays.deepHashCode的例子
import java.util.Arrays;
public class B {
public static void main(String[] args) {
Object[] d = {"abc", "def", new String[]{"ghi"}};
Object[] e = {"abc", "def", new String[]{"ghi"}};
System.out.println("NOTE: D and E have identical nested values");
System.out.println("Using Object[].hashCode(): different");
System.out.println("d = " + d.hashCode());
System.out.println("f = " + e.hashCode());
System.out.println("Using Arrays.hashCode(): still different");
System.out.println("d = " + Arrays.hashCode(d));
System.out.println("e = " + Arrays.hashCode(e));
System.out.println("Using Arrays.deepHashCode(): identical");
System.out.println("d = " + Arrays.deepHashCode(d));
System.out.println("e = " + Arrays.deepHashCode(e));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
NOTE: D and E have identical nested values
Using Object[].hashCode(): different
d = 241990244
f = 1943487137
Using Arrays.hashCode(): still different
d = 1057745997
e = 709187068
Using Arrays.deepHashCode(): identical
d = 95807651
e = 95807651
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5562 次 |
| 最近记录: |