如何在Java中扩展HashSet?

jer*_*jtu -1 java hashset

假设我有一CategoryKey节课:

public class CategoryKey {
    public int layer;
    public int parent;
    public int child;
}
Run Code Online (Sandbox Code Playgroud)

我尝试将其中的许多实例放在a中Set,但我们知道HashSet它不适合存储自定义类的实例.那么如何扩展java类HashSet以满足我的要求呢?或者我如何创建一个新的类实现接口Set来解决同样的问题?

Jon*_*eet 10

但是我们知道HashSet不适合自定义类的商店实例

是的,只要你认为你的课适当.特别是:

  • 你应该覆盖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;
  }
}
Run Code Online (Sandbox Code Playgroud)