Java数组校验和独立于元素顺序

时间:2014-09-10 11:41:02

标签: java arrays hash checksum

说我有两个数组,例如[B,D,C,A][B,A,D,C]。什么机制会在两个数组(以及包含其元素排列的任何数组)上生成相同的校验和?

在以下示例中,check_acheck_b将不相等。将元素按字母顺序排列不是一种选择,因为数组中的对象可能不是字符串或任何可排序的对象。

String[] a = {"B","D","C","A"};
String[] b = {"B","A","D","C"};

String check_a = a.hashCode();
String check_b = b.hashCode();

2 个答案:

答案 0 :(得分:1)

让我们假设您有一个获取元素校验和的函数。要获得校验和,您需要找到Commutative property的操作,其中有很多。例如+*^

答案 1 :(得分:1)

快速示例

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

正如您所看到的,您必须迭代所有元素并对它们的哈希求和(或乘以)。无论它们是以什么顺序,都会给你相同的结果。