我有一个 PriorityQueue of Objects,我需要根据 float values.How 对它进行排序,我应该为它创建一个比较器吗?
I have a PriorityQueue of Objects and I need to sort it based on float values.How do I create a comparator for it?
我已经为优先级队列创建了一个比较器。
class CompareBySalary implements Comparator<Employee>{
@Override
public int compare(Employee e1,Employee e2){
return e1.salary<e2.salary ? -1 : e1.salary>e2.salary ? 1 : 0;
}
}
class Employee{
String name;
float salary;
Employee(String name,float salary){
this.name=name;
this.salary=salary;
}
}
public class TryCode{
public static void main(String args[])
{
Employee e1=new Employee("C",10000);
Employee e2=new Employee("A",5000.45f);
Employee e3=new Employee("D",15000);
Employee e4=new Employee("B",5000.67f);
Queue<Employee> q=new PriorityQueue(new CompareBySalary());
q.offer(e1);
q.offer(e2);
q.offer(e3);
q.offer(e4);
for(Employee e:q)
System.out.println(e.name);
}
}
这给出了 output:A B D C
为什么排序不正确?
这是我想念的东西吗?
P.S。我已经尝试过 Float.compare() 它给出了相同的输出。
如下更改域模型:
class Employee implements Comparable<Employee> {
private String name;
private float salary;
Employee(String name, float salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public float getSalary() {
return salary;
}
@Override
public int compareTo(Employee o) {
if (o1.getSalary()>o2.getSalary()) {
return 1;
} else if (o1.getSalary()<o2.getSalary()) {
return -1;
} else {
return 0;
}
}
}
删除CompareBySalary
(你不需要它)
像这样创建您的 PriorityQueue
:
PriorityQueue<Employee> q = new PriorityQueue<>(Comparator.comparingDouble(Employee::getSalary));
我已经为优先级队列创建了一个比较器。
class CompareBySalary implements Comparator<Employee>{
@Override
public int compare(Employee e1,Employee e2){
return e1.salary<e2.salary ? -1 : e1.salary>e2.salary ? 1 : 0;
}
}
class Employee{
String name;
float salary;
Employee(String name,float salary){
this.name=name;
this.salary=salary;
}
}
public class TryCode{
public static void main(String args[])
{
Employee e1=new Employee("C",10000);
Employee e2=new Employee("A",5000.45f);
Employee e3=new Employee("D",15000);
Employee e4=new Employee("B",5000.67f);
Queue<Employee> q=new PriorityQueue(new CompareBySalary());
q.offer(e1);
q.offer(e2);
q.offer(e3);
q.offer(e4);
for(Employee e:q)
System.out.println(e.name);
}
}
这给出了 output:A B D C 为什么排序不正确? 这是我想念的东西吗? P.S。我已经尝试过 Float.compare() 它给出了相同的输出。
如下更改域模型:
class Employee implements Comparable<Employee> { private String name; private float salary; Employee(String name, float salary) { this.name = name; this.salary = salary; } public String getName() { return name; } public float getSalary() { return salary; } @Override public int compareTo(Employee o) { if (o1.getSalary()>o2.getSalary()) { return 1; } else if (o1.getSalary()<o2.getSalary()) { return -1; } else { return 0; } } }
删除
CompareBySalary
(你不需要它)像这样创建您的
PriorityQueue
:PriorityQueue<Employee> q = new PriorityQueue<>(Comparator.comparingDouble(Employee::getSalary));