Queue队列是一种先进先出数据结构,Queue是一个接口,具体的实现类又有哪些呢?
注:Queue中有一些方法:add(),offer(),remove(),poll()
add():当队列容量有限制无法再添加元素时,使用add方法来添加会抛出异常,使用offer方法,能添加成功返回true,添加失败返回false
remove():当队列为空时,使用remove会报错,使用poll方法,返回null
Deque双向队列接口,继承了Queue接口,下面讨论几种常见的实现上面这种接口的类。
(1)ArrayDeque和LinkedList都实现了Deque接口,两者区别就在于前者底层存储使用的是数组,后者数据存储使用的是链表,在数据中间添加删除数据效率更高。
(2)PriorityQueue直接实现Queue接口,优先级队列,队列中的元素顺序并不是按照入队的顺序,而是按照比较器来排列。
//降序排列
PriorityQueue<Integer> queue = new PriorityQueue<Integer>(new Comparator<Integer>() {
public int compare(Integer i1,Integer i2){
if(i1<i2)return 1;
if(i1>i2)return -1;
return 0;
}
});
queue.add(2);
queue.add(4);
queue.add(1);
queue.add(7);
queue.add(5);
int len = queue.size();
for(int i=0;i<len;i++){
System.out.println(queue.poll());//7,5,4,2,1(不提供Comparator类时,升序排序)
}