Queue 实现一个先进先出的队列
获取队列长度:size()
添加元素到队尾:boolean add(E e) /boolean offer(E e)
获取队列头部元素并删除:E remove() / E poll()
获取队列头部元素但不删除:E element() / E peek()
当添加或获取元素失败时
throw Exception
返回false或null
添加元素到队尾
add(E e)
boolean offer(E e)
取队首元素并删除
E remove()
E poll()
取队首元素但不删除
E element()
E peek()
注意
避免把null添加咋队列
PriorityQueue的出队顺序与元素的优先级有关
remove() / poll() 总是取优先级最高的元素
PriorityQueue具有Queue接口,所以我们可以直接用Queue的方法来操作PriorityQueue
获取队首元素时总是返回优先级最高的元素
E remove() /E poll() / E element() /E peek()
import java.util.PriorityQueue;
public class QueueTest {
public static void main(String[] args) {
PriorityQueue queue = new PriorityQueue<>((o1, o2) -> -o1.getName().compareTo(o2.getName()));
queue.offer(new Person("刘德华", 18));
queue.offer(new Person("张学友", 17));
queue.offer(new Person("黎明", 38));
while (queue.size()>0){
System.out.println(queue.poll().toString());
}
}
}
class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
运行结果
Person{name='黎明', age=38}
Person{name='张学友', age=17}
Person{name='刘德华', age=18}