java - 自定义对象比较器

标签 java collections treeset

我会尽量开门见山。

我有我的自定义节点对象,它具有属性成本。我想按这些 Node 对象的属性 Cost 升序对它们进行排序。

我可以使用PriorityQueue<Node> = new PriorityQueue<Node>(10000, new NodeComparator());来做到这一点,但这种方式对我来说太慢了,现在我想做同样的事情,只使用 TreeSet。 无论如何,如果我的构造函数看起来像这样 TreeSet<Node> = new TreeSet<Node>(new NodeComparator()); ,程序似乎跳过了大量的 Node 对象,似乎将它们视为相同的。但他们不是。我假设可能存在一些 hashCode 问题,但我不确定,而且目前我不知道如何解决它。

为了简洁起见,我只希望 TreeSet 中的节点按 Cost 属性按升序排序。 这是我的 NodeComparator 类:

public class NodeComparator implements Comparator<Node> {

    @Override
    public int compare(Node n1, Node n2) {
        // TODO Auto-generated method stub
        if(n1.cost > n2.cost) return 1;
        else if(n1.cost < n2.cost) return -1;
        else return 0;
    }

}

这是我的 Node 类:

public class Node{

    public State state;
    public int cost;

    public Node(State s, int Cost){
        this.state = s;
        this.cost = Cost;
    }

    public State getState(){

        return this.state;
    }

    public int getCost(){
        return this.cost;
    }
}

我也会为您提供我的州立类(class)。

public class State {

    public int lamp;

    public ArrayList<Integer> left;


    public State(ArrayList<Integer> Left, int Lamp){
        lamp = Lamp;
        left = Left;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + lamp;
        result = prime * result + ((left == null) ? 0 : left.hashCode());
        return result;
    }


    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        State other = (State) obj;
        if (lamp != other.lamp)
            return false;
        if (left == null) {
            if (other.left != null)
                return false;
        } else if (!left.equals(other.left))
            return false;
        return true;
    }
}

最佳答案

TreeSet uses TreeMapstore values 。你的问题是 TreeMapequals uses result of comparator检查元素是否已在 map 中。因此,您需要在 compare 方法中包含 steate 字段的状态,例如

@Override
public int compare(Node n1, Node n2) {
    // TODO Auto-generated method stub
    if(n1.cost > n2.cost) return 1;
    else if(n1.cost < n2.cost) return -1;
    else return ( n1.equals(n2)? 0 : 1);
}

关于java - 自定义对象比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15635714/

相关文章:

java - 检查 JTextField 给定的数据

java - 将整个映射转换/展平为列表的最有效方法(键和值在一起,而不是分开)

c# - 为什么泛型 ICollection<T> 不继承一些具有 Count 属性的非泛型接口(interface)?

java - 我对 TreeMap<node> 做错了什么?

java - 电话簿编程 - TreeSet 或 HashSet

java - 你什么时候知道什么时候使用 TreeSet 或 LinkedList?

java - Android - 根据类型强制属性

java - Spring Boot - PostgreSQL 驱动程序无法位于类路径中

asp.net-mvc-3 - 带有集合的提交对象缺少新集合数据

java - 从 HttpURLConnection 保存 Cookie(包括 !httponly 标志)和 session