小根堆PriorityQueue 是优先级队列,这是什么呢,就是默认优先依次取出最小值得那个对象,什么是最小值对象,就是你以为它小就是小,跟对象具体的大小无关,完全看比较器怎么判断的大小。时间复杂度O(n)
还是学生类比较,上代码:
//我的优先级队列
public static void main(String[] args) {
Student s1 = new Student("王二",5,29);
Student s2 = new Student("王五",5,30);
Student s3 = new Student("王七",7,29);
Student s4 = new Student("王一",1,51);
Student s5 = new Student("王四",4,51);
Student s6 = new Student("王三",3,29);
PriorityQueue<Student> queue = new PriorityQueue<>(new StudentCompare(true));
queue.add(s1);
queue.add(s2);
queue.add(s3);
queue.add(s4);
queue.add(s5);
queue.add(s6);
while(!queue.isEmpty()) {
//弹出
Student poll = queue.poll();
System.out.println(poll.name+"-"+poll.age+"-"+poll.id);
}
}
//自定义比较方式类,通过参数true和false判断正序还是倒序,最终目的就是为了改变compare方法的返回值是-1还是1
public static class StudentCompare implements Comparator<Student>{
public int i=1;
public StudentCompare(boolean flag) {
if(flag) {
this.i=-1;
}
}
//说明:如果返回-1,o1在前,如果返回1,o2在前,如果返回0,o1在前
@Override
public int compare(Student o1, Student o2) {
if(o1.id>o2.id) {
return -1*i;
}else if(o1.id<o2.id) {
return 1*i;
}else {
if(o1.age>o2.age) {
return 1*i;
}else if(o1.age<o2.age) {
return -1*i;
}
}
return 0;
}
}
//定义学生类
public static class Student{
public Student(String name,int age,int id) {
this.name=name;
this.age = age;
this.id = id;
}
public String name;
public int age;
public int id;
}