public class Student implements Comparable<Student> {
String name; //先写出一个Student类,然后把Student对象加进PriorityQueue的容器里
int age; //一开始没有实现comparable接口,所以也没用实现comparto方法public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
return new Integer(this.getAge()).compareTo(new Integer(o.getAge()));
//this.getAge()是int类型无法调用comparto的方法 所以无法比较,把它转化为一个Integer对象后就可以调用(integer实现了comparable接口);才能进行比较;
}
}
import java.util.PriorityQueue;
import java.util.Queue;
public class TestPriorityQueue {
public static void main(String[] args) {
Queue<Student> p = new PriorityQueue<>();
p.add(new Student("李烈",12));
p.add(new Student("李哈",13));
p.add(new Student("李白",12));
p.add(new Student("黑子",15));
p.add(new Student("二哈",12));
p.add(new Student("人发",1));
/* for(Student s: p) {
System.out.println(s);//用加强for循环会无法排序,因为直接取出来没有进行比较
} */
while(!p.isEmpty()) { //调用poll方法时候会进行比较;
System.out.println(p.poll()); //直接在这里打印会报错类型不对,因为比较对象要实现comparable接口并且实
} // 现它的comparto方法;所以在Student里去实现comparable接口;
}
}