如何在TreeSet中使用自定义类? [英] How can I use a custom class in a TreeSet?

查看:66
本文介绍了如何在TreeSet中使用自定义类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I was using a Set similar to this:

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

class node {

  private int x;
  private int y;

}

这是否可以接受,并且由于它是一个TreeSet,是否也可以对其进行排序?

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

推荐答案

如果不实现 Comparable< Node> ,就无法对它进行排序,这实际上是不合适的进行设置操作,直到您覆盖 equals() hashCode().(您没有必须覆盖 equals hashCode 来使 TreeSet 正常工作,但是这样做很有意义这样做.)

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

类似这样的东西:

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

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

这篇关于如何在TreeSet中使用自定义类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆