2012-03-26 55 views
-2

比方說,我有一個CategoryKey類:如何在Java中擴展HashSet?

public class CategoryKey { 
    public int layer; 
    public int parent; 
    public int child; 
} 

我試圖把它的許多情況下,Set之內,但我們知道HashSet不適合存儲自定義類的實例。那麼如何擴展java類HashSet以滿足我的要求?或者我如何創建一個實現接口Set的新類來解決同樣的問題?

+3

「HashSet不適合存儲定製類的實例」爲什麼不呢? – EJP 2012-03-26 11:58:52

+0

你是什麼意思「我們知道」? 'HashSet'非常適合存儲具有'.hashCode()'和'.equals()'的任何對象的實例。 – 2012-03-26 12:01:00

+0

請涵蓋我的[HashSet的內部生活]教程(http://volodial.blogspot.com/2013/07/internal-life-of-hashset-in-java.html) – 2013-07-27 08:49:42

回答

9

,但我們知道的HashSet不適合customed類的存儲實例

其實很容易,只要你寫你的類爲宜。特別是:

  • 您應該重寫equals()hashCode()
  • 你應該讓你的類型不變
  • 你不應該使用公共領域

例如:

public final class CategoryKey { 
    private final int layer; 
    private final int parent; 
    private final int child; 

    public CategoryKey(int layer, int parent, int child) { 
    this.layer = layer; 
    this.parent = parent; 
    this.child = child; 
    } 

    public int getLayer() { 
    return layer; 
    } 

    public int getParent() { 
    return parent; 
    } 

    public int getChild() { 
    return child; 
    } 

    @Override public boolean equals(Object other) { 
    if (!(other instanceof CategoryKey)) { 
     return false; 
    } 
    CategoryKey otherKey = (CategoryKey) other; 
    return layer == otherKey.layer 
     && parent == otherKey.parent 
     && child == otherKey.child; 
    } 

    @Override public int hashCode() { 
    int hash = 23; 
    hash = hash * 31 + layer; 
    hash = hash * 31 + parent; 
    hash = hash * 31 + child; 
    return hash; 
    } 
} 
+0

更好的方法是使用[apache-commons]中的HashBuilder和EqualsBuilder(http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/builder/HashCodeBuilder的.html)。基於反射的方法非常簡潔,不需要頻繁更新。 – questzen 2012-03-26 12:08:10

+1

這就是說,反射很慢。做到喬恩的方式。 – 2012-03-26 12:19:41

+0

我剛剛閱讀了相關的[材料](http://www.technofundo.com/tech/java/equalhash.html),並想知道31是否可以用其他素數替換? @Jon Skeet – 2012-03-26 12:24:19

0

覆蓋equalsCategoryKeyhashCode方法在Set

提供了獨特的實例,其中包含重複元素的集合。更正式地說,集合 不包含元素對e1和e2,使得e1.equals(e2)和 中最多一個爲null元素。

參考here

+0

不完全是,你需要覆蓋hashCode也是如此。 – questzen 2012-03-26 11:59:23

+0

@questzen謝謝,更新 – 2012-03-26 12:00:09

1

爲什麼HashSet不適合存儲自定義類的實例?

只要你的班級正確執行equals()hashCode()它應該可以正常工作。