gpt4 book ai didi

java - 在优先级队列中使用比较器进行排序但没有得到正确的结果

转载 作者:行者123 更新时间:2023-12-01 15:17:49 25 4
gpt4 key购买 nike

PriorityQueue<Player> playerQueue = new PriorityQueue<Player>(30,
new Comparator<Player>( ) {
// overriding the compare method
public int compare(Player i, Player j) {
return (int)i.playerPrice() < (int)j.playerPrice() ? -1 : ((int)i.playerPrice() == (int)j.playerPrice()) ? 0 : 1;
}
}
);

for(Player a:XMLParserViaSax.getListOfPlayers()){
System.out.println(a.getName()+ "-->"+a.playerPrice());
}

for(Player player:XMLParserViaSax.getListOfPlayers()){
playerQueue.add(player);
}
//playerQueue.addAll(XMLParserViaSax.getListOfPlayers());

System.out.println("**************************");
for(Player j:playerQueue){
System.out.println(j.getName()+ "-->"+j.playerPrice());
}

我正在尝试按playerprice对Player进行排序,我在Player类中没有任何变量作为playerprice。playerPrice()是一种计算播放器价格的方法。所以现在当我尝试对这些Player进行排序时它给我一个随机顺序的对象。

我的玩家类别中是否需要有一个playerprice 私有(private)成员?'玩家等级如下:

public class Player {

private String name;
private int battingStrength;
private int bowlingStrength;
private int fieldingStrength;
private int keepingStrength;
private int jerseyNumber;

public int playerStrength() {
return AuctionPlayerHelper.calculateStrength(this);
}

public boolean canKeepWickets() {
return (keepingStrength == 10);
}

public boolean isForeignPlayer(){
return AuctionPlayerHelper.isForeignPlayer(this.jerseyNumber);
}

public double playerPrice() {
return AuctionPlayerHelper.calculatePrice(this);

}

//getters,setters
}

'

最佳答案

来自PriorityQueue API的注释:

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

因此,像您所做的那样迭代队列将不按“顺序”。

当您从队列中删除头部时,例如当您在队列上调用poll()时,优先级顺序就会变得明显。

关于java - 在优先级队列中使用比较器进行排序但没有得到正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11388698/

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