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

标签 java treeset

如果我使用的是与此类似的 Set:

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

class node {

  private int x;
  private int y;

}

这是可以接受的吗,既然它是一个 TreeSet,它也会对它进行排序吗?

最佳答案

如果不实现 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;
  }
}

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

关于java - 如何在 TreeSet 中使用自定义类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7416176/

相关文章:

java - 计算短语中的空白字符 - Java

java - 使用计时器编写启动画面代码时出错

java - 为什么 TreeSet 抛出 ClassCastException?

java - 带有 GNU trove 的整数排序集

java - java中如何判断set是否存在?

java - 在 ArrayList 中搜索值,然后将值和键复制到新的 TreeSet

java - 清除 Jackrabbit 数据

Java SSL 工厂连接到 SSL 服务器(仅使用公钥和证书)

java - 如何在 Maven 构建中包含带有资源的文件夹

Java:TreeSet 的问题