gpt4 book ai didi

java - 自定义对象比较器

转载 作者:行者123 更新时间:2023-12-02 00:52:52 24 4
gpt4 key购买 nike

我会尽量开门见山。

我有我的自定义节点对象,它具有属性成本。我想按这些 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com