JavaBasic:PriorityQueue

PriorityQueue实现一个优先队列
从队首获取元素时,总是获取到优先级最高的元素
默认元素比较顺序排序,必须实现comparator接口
可以通过Comparator自定义排序,这样不必实现comparator接口


//实现Comaparable接口
public class Person implements Comparable<Person>{
    private String name;
    private Integer age;

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }


    @Override
    public int compareTo(Person o) {
        return this.name.compareTo(o.name);
    }
}


public class Student {
    private String name;
    private Integer score;

    public Student(String name, Integer score) {
        this.name = name;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }

    public String getName() {
        return name;
    }

    public Integer getScore() {
        return score;
    }
}

public class Main {
    public static void main(String[] args) {
        Queue<Person> queue=new PriorityQueue<>();
        queue.add(new Person("xiaozhang",10));
        queue.add(new Person("zhangsan",10));
        queue.add(new Person("lisi",10));

        System.out.println(queue.remove());


        Queue<Student> queue1=new PriorityQueue<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                //按照score的倒序输出
                return -o1.getScore().compareTo(o2.getScore());
            }
        });
        queue1.add(new Student("xiaozhang",100));
        queue1.add(new Student("zhangsan",80));
        queue1.add(new Student("lisi",70));

        System.out.println(queue1.poll());
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值