How can I use a custom class in a TreeSet?

大城市里の小女人 提交于 2019-12-14 00:46:16

问题


If I was using a Set similar to this:

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?


回答1:


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 have to override equals and hashCode for TreeSet to work, but it would make sense to do so.)

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.)




回答2:


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.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/7416176/how-can-i-use-a-custom-class-in-a-treeset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!