非线程安全PriorityQueue
一:PriorityQueue简介
PriorityQueue是和优先级有关系的一种队列。的确,它是优先队列,这里的优先是指:根据某种规则将队列元素进行排序,每次出队时总是取出排序中的最大或者最小元素,这样的特性决定优先队列不完全遵循FIFO规则,其中排序规则可以决策元素的优先级。
二:特性
- 队列元素根据自然排序或者根据具体的比较器排序
- 实例化时若未指定初始容量,默认容量为11
- 自动扩容。如果容量小于64,两倍增长扩容;否则增长50%
- 无边界容器
- 迭代器不具有以特定顺序访问队列元素
- 不支持
null
元素 - 非线程安全
- 支持被序列化
- 入队出队的时间复杂度O(log(n))
三:实操代码
//PriorityQueue ---start
PriorityQueue<Integer> priorityQueue = new PriorityQueue();
//内部还是offer()
priorityQueue.add(100);
priorityQueue.offer(2);
priorityQueue.add(4);
priorityQueue.add(1);
Arrays.stream(priorityQueue.toArray()).forEach(a->{
System.out.println("PriorityQueue toArray:"+a);
});
/**
* 输出:
* PriorityQueue toArray:1
* PriorityQueue toArray:2
* PriorityQueue toArray:4
* PriorityQueue toArray:100
*/
Integer peek4 = priorityQueue.peek();
System.out.println("PriorityQueue peek:"+peek4);
//PriorityQueue peek:1
Integer poll3 = priorityQueue.poll();
System.out.println("PriorityQueue poll:"+poll3);
//PriorityQueue poll:1
Arrays.stream(priorityQueue.toArray()).forEach(a->{
System.out.println("PriorityQueue poll toArray:"+a);
});
/**
* PriorityQueue poll toArray:2
* PriorityQueue poll toArray:100
* PriorityQueue poll toArray:4
*/
boolean contains1 = priorityQueue.contains(100);
System.out.println("PriorityQueue contains:"+contains1);
//PriorityQueue contains:true
boolean remove2 = priorityQueue.remove(100);
System.out.println("PriorityQueue remove:"+remove2);
//PriorityQueue remove:true
Arrays.stream(priorityQueue.toArray()).forEach(a->{
System.out.println("PriorityQueue remove toArray:"+a);
});
/**
* PriorityQueue remove toArray:2
* PriorityQueue remove toArray:4
*/
List<Integer> listPriorityQueue = new ArrayList<>();
listPriorityQueue.add(3);
listPriorityQueue.add(18);
listPriorityQueue.add(1);
priorityQueue.addAll(listPriorityQueue);
Arrays.stream(priorityQueue.toArray()).forEach(a->{
System.out.println("PriorityQueue addAll toArray:"+a);
});
/**
* PriorityQueue addAll toArray:1
* PriorityQueue addAll toArray:2
* PriorityQueue addAll toArray:3
* PriorityQueue addAll toArray:18
* PriorityQueue addAll toArray:4
*/
//内部还是offer()
Integer element = priorityQueue.element();
System.out.println("PriorityQueue element:"+element);
//PriorityQueue element:1
//倒序 start 默认升序
PriorityQueue<Integer> priorityQueues = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
List<Integer> listPriorityQueueNew = new ArrayList<>();
listPriorityQueueNew.add(3);
listPriorityQueueNew.add(18);
listPriorityQueueNew.add(1);
priorityQueues.addAll(listPriorityQueueNew);
Arrays.stream(priorityQueues.toArray()).forEach(a->{
System.out.println("priorityQueues add toArray:"+a);
});
/**
* priorityQueues add toArray:18
* priorityQueues add toArray:3
* priorityQueues add toArray:1
*/
//倒序 end 默认升序
//PriorityQueue ---end
<