假设我有两个数组,例如[B,D,C,A]
和 [B,A,D,C]
。什么机制可以在两个数组(以及任何包含其元素排列的数组)上生成相同的校验和?
在以下示例中,check_a
和 check_b
不相等。将元素按字母顺序排列不是一个选项,因为数组中的对象可能不是字符串或任何可排序的东西。
String[] a = {"B","D","C","A"};
String[] b = {"B","A","D","C"};
String check_a = a.hashCode();
String check_b = b.hashCode();
最佳答案
简单示例
public class ArrayHash {
public static void main(String[] args) {
String[] one = new String[]{"A", "B", "C", "D"};
String[] two = new String[]{"D", "C", "B", "A"};
System.out.println("One = " + one.hashCode());
System.out.println("Two = " + two.hashCode());
System.out.println("Method for one = "+hash(one));
System.out.println("Method for two = "+hash(two));
}
private static int hash(Object[] array) {
int ret = 0;
for (Object c : array) {
ret += (124567890 + c.hashCode()) * c.hashCode();
}
return ret;
}
}
它给出了输出
One = 366712642
Two = 1829164700
Method for one = 266
Method for two = 266
如您所见,您必须迭代所有元素并对它们的哈希值求和(或相乘)。无论它们的顺序如何,都会给你相同的结果。
关于Java 数组校验和与元素顺序无关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25764473/