我有一个实现Comparable的User
类。在我将用户列表添加到PriorityQueue<User>
后,他们应按scores
排列优先级,但出于某种原因,他们不会。Queue
。你能否帮我弄清楚为什么用户没有在prioritisedUsers.poll()
中排序?
更新
我通过轮询元素访问队列。 PriorityQueue<User> prioritisedUsers = userPriorityStrategy.computeUserPriority(users);
while(!prioritisedUsers.isEmpty()){
System.out.println(prioritisedUsers.poll().getPriorityScore());
}
它始终带有顺序尊重的随机分数。
0.35036433736768735
0.6619121139678329
0.09520067929838127
0.4013591573863
0.6704568389588227
0.5989900926939181
0.7320779721160738
输出:
public class User implements Comparable<User>{
private long id;
private String fistName;
private String lastName;
private double priorityScore;
public User (long id, String firstName, String lastName){
this.id = id;
this.fistName = firstName;
this.lastName = lastName;
}
public double getPriorityScore(){
return this.priorityScore;
}
public void setPriorityScore(double priorityScore){
this.priorityScore = priorityScore;
}
public long getId(){
return this.id;
}
public String getFistName(){
return this.fistName;
}
public String getLastName(){
return this.lastName;
}
public int compareTo(User o) {
return (int) (this.getPriorityScore() - o.getPriorityScore());
}
}
public PriorityQueue<User> computeUserPriority(List<User> users) {
PriorityQueue<User> prioritisedUsers = new PriorityQueue<User>(users.size());
for (User user : users) {
user.setPriorityScore(rand.nextDouble());
prioritisedUsers.add(user);
}
return prioritisedUsers;
}
感谢您的帮助!
{{1}}
答案 0 :(得分:5)
我不太确定你的转换为(int)效果如何......因为转换为int会隐式丢弃任何小数。
如果我没错,请尝试类似
的内容public int compareTo(User object) {
if (this.getPriorityScore() < object.getPriorityScore())
return -1;
if (this.getPriorityScore() == object.getPriorityScore())
return 0;
return 1;
}
或者更简单地说:
public int compareTo(User o) {
return Double.compare(this.getPriorityScore(), o.getPriorityScore());
}