如何在TreeSet中使用自定义类?

SNp*_*Npn 7 java treeset

如果我使用Set类似于此:

Set<node> s=new TreeSet<node>();

class node {

  private int x;
  private int y;

}
Run Code Online (Sandbox Code Playgroud)

这是否可以接受,因为它是一个TreeSet,它还会对它进行排序吗?

Jon*_*eet 20

如果没有你的实现Comparable<Node>,它将无法对它进行排序,并且在你覆盖equals()和之前它不适合于设置操作hashCode().(你不具备覆盖equalshashCode进行TreeSet工作,但它会是有意义的这样做.)

像这样的东西:

final class Node implements Comparable<Node> {

  private final int x;
  private final int y;

  Node(int x, int y) {
    this.x = x;
    this.y = y;
  }

  @Override public boolean equals(Object other) {
    if (!(other instanceof Node)) {
      return false;
    }
    Node otherNode = (Node) other;
    return x == otherNode.x && y == otherNode.y;
  }

  @Override public int hashCode() {
    return x * 31 + y * 17; // For example...
  }

  @Override public int compareTo(Node other) {
    // As of Java 7, this can be replaced with
    // return x != other.x ? Integer.compare(x, other.x) 
    //     : Integer.compare(y, other.y);

    if (x < other.x || (x == other.x && y < other.y)) {
      return -1;
    }
    return x == other.x && y == other.y ? 0 : 1;
  }
}
Run Code Online (Sandbox Code Playgroud)

(请注意,按照惯例,类名称Node不是node.)

  • @medopal:当涉及继承时,平等和其他事情变得更难以正确实现(当甚至*是*正确性的想法时).同样,当我知道没有子类时,我知道它是不可变的.基本上我订阅"继承设计或禁止它". (4认同)
  • 使它成为"最后阶级"的原因是什么? (2认同)

Sco*_*ion 6

Node需要实现Comparable,或者您需要传递一个可以比较两个Node对象的自定义Comparator.此外,任何基于散列的集合都依赖于适当地覆盖equals()和hashcode()方法的对象.