Reputation: 3579
I do have a User
class which implements Comparable. After I add list of users into PriorityQueue<User>
they should be prioritized by scores
, but for some reason they don't. Could you please help me to figure out why users are not sorted in my Queue
?
Update:
I am accessing queue by polling elements. prioritisedUsers.poll()
it always comes with random scores with order respect.
PriorityQueue<User> prioritisedUsers = userPriorityStrategy.computeUserPriority(users);
while(!prioritisedUsers.isEmpty()){
System.out.println(prioritisedUsers.poll().getPriorityScore());
}
OUTPUT:
0.35036433736768735
0.6619121139678329
0.09520067929838127
0.4013591573863
0.6704568389588227
0.5989900926939181
0.7320779721160738
Thanks for any help!
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;
}
Upvotes: 2
Views: 223
Reputation: 1477
I'm not so sure that your cast to (int) works well... because casting to an int implicitly drops any decimal.
If I'm not in wrong, try something like
public int compareTo(User object) {
if (this.getPriorityScore() < object.getPriorityScore())
return -1;
if (this.getPriorityScore() == object.getPriorityScore())
return 0;
return 1;
}
or alternatively and more simply:
public int compareTo(User o) {
return Double.compare(this.getPriorityScore(), o.getPriorityScore());
}
Upvotes: 5