简体   繁体   中英

How to extend the HashSet in Java?

Let's say I have a CategoryKey class:

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

I try to put many instances of it within a Set , but as we know HashSet is not suitable to store instances of custom classes. So how can I extend the java class HashSet to meet my requirement? Or how can I create a new class implementing interface Set to solve the same problem?

but as we know HashSet is not suitable for store instances of customed class

Yes it is, so long as you write your class appropriate. In particular:

  • You should override equals() and hashCode()
  • You should make your type immutable
  • You shouldn't use public fields

For example:

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

Why is HashSet not suitable to store instances of custom classes?

As long as your class has a proper implementation of equals() and hashCode() it should work fine.

Override equals and hashCode method of CategoryKey to provide unique instance in Set

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.

Refer here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM