簡體   English   中英

hashCode和equals在int [] Java中的實現

[英]Implementation of hashCode and equals in int[] Java

看來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;
    }
}

可以,但是我更喜歡避免使用自定義包裝程序或第三方庫。 有選擇嗎?

由於標准Java Hashtable不允許覆蓋用於鍵的哈希碼,因此您很不走運,因此需要像以前一樣使用包裝器。

請記住,您的hashCode實現非常糟糕,您可以使用此代碼(從標准JDK中的java.util.Arrays中獲取)來獲得更好的哈希分配:

public static int hashCode(int a[]) {
  if (a == null)
    return 0;

  int result = 1;
  for (int element : a)
    result = 31 * result + element;
  return result;
}

一種替代方法是使用其他可以處理基元的哈希表。 一個這樣的選項是Banana ,這是我創建的原始集合庫。

在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()也可以簡化?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM