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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7416176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:52:06  来源:igfitidea点击:

How can I use a custom class in a TreeSet?

javatreeset

提问by SNpn

If I was using a Setsimilar to this:

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

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

class node {

  private int x;
  private int y;

}

Would this be acceptable, and since it's a TreeSet, would it also sort it?

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

回答by Jon Skeet

It's not going to be able to sort it without you implementing Comparable<Node>, and it won't really be an appropriate for set operations until you override equals()and hashCode(). (You don't haveto override equalsand hashCodefor TreeSetto work, but it would make sense to do so.)

如果不实现Comparable<Node>,它将无法对其进行排序,并且在您覆盖equals()和之前,它真的不适合设置操作hashCode()。(你不会重写equals,并hashCodeTreeSet工作,但它会是有意义的这样做。)

Something like this:

像这样的东西:

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

(Note that by convention the class name would be Node, not node.)

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

回答by Scorpion

Node needs to implement a Comparable or you need to pass a custom Comparator which can compare two Node objects. Also, any hash based collection relies on the object suitably overriding equals() and hashcode() method.

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

回答by leifg

You have to specify equals, hashCode and implement the Comparable interface

您必须指定 equals、hashCode 并实现 Comparable 接口

回答by Santosh

There is nothing wrong with the code as for as acceptance is concerned. But for sorting Nodeclass MUST implement comparable interface.

就接受而言,代码没有任何问题。但是对于排序Node类必须实现可比较的接口。