1

int[] の hashCode() と equals() が不十分に実装されているか、まったく実装されていないようです! (Android でテスト済みですが、どの Java 環境にも当てはまると思います)。

HashSet.contains() を適切に動作させるために、int[] のラッパーを作成する必要がありました (私のコーディング スタイルを批判しないでください。本質を見てください)。

public class IntArray {
    private int[] value;

    public IntArray(int[] value) {
        this.value = value;
    }

    @Override
    public int hashCode() {
        int sum = 0;
        // Integer overflows are cheerfully welcome.
        for (int elem: value) sum += elem;
        return sum;
    }

    @Override
    public boolean equals(Object o) {
        if (o == null) return (value==null);

        if (value != null) {
            if (o instanceof int[]) 
                return compare((int[])o);

            if (o instanceof IntArray)
                return compare(((IntArray)o).value);
        }

        return false;
    }

    protected boolean compare(int[] other) {
        int len = value.length;
        if (other.length != len) return false;
        for (int i=0; i<len ; i++)
            if (value[i] != other[i]) return false;
        return true;
    }
}

問題なく動作しますが、カスタム ラッパーやサードパーティ ライブラリは避けたいと思います。オプションはありますか?

4

2 に答える 2

0

Omry Yadan のメッセージの後、hashCode 関数はそれと同じくらい単純になります!

    @Override
    public int hashCode() {
        return Arrays.hashCode(value);
    }

ARM などの RISC CPU の場合、より効率的である可能性があります。

    @Override
    public int hashCode() {
        int code = 0;
        if (value != null) {
            code++;
            for (int elem: value)
                code = (code<<5) - code + elem;
        }
        return code;
    }

配列を比較するための標準関数もあるかもしれません。その場合、 equals() も単純化できますか?

于 2013-10-13T05:00:14.117 に答える