单向队列:一端操作
1.一般:FIFO
2.优先队列和堆栈:LIFO
插入:offer(e)
移除:poll()
获取:peek()
双向队列:两端操作
插入:offerFirst(e) offerLast(e)
移除:pollFirst() pollLast()
获取:peekFirst() peekLast()
ArrayDeque测试
public class QueueTest {
public static void main(String[] args) {
Queue<Request> que=new ArrayDeque<Request>();
//模拟排队情况
for(int i=0;i<10;i++){
final int num=i;
que.offer(new Request() {
@Override
public void deposite() {
System.out.println("第"+num+"个人办理存款业务,存款额度为:"+Math.random()*10000);
}
});
}
dealWith(que);
}
public static void dealWith(Queue<Request> que){
Request req=null;
while (null!=(req=que.poll())){
req.deposite();
}
}
}
interface Request{
//存款
void deposite();
}
自己实现堆栈
public class StackTest<E> {
//容器
private Deque<E> container=new ArrayDeque<E>();
//容量
private int cap;
public StackTest(int cap) {
this.cap = cap;
}
//压栈
public boolean push(E e){
if(container.size()>=cap){
return false;
}
return container.offerLast(e);
}
//弹栈
public E pop(){
return container.pollLast();
}
//获取
public E peek(){
return container.peekLast();
}
public int size(){
return this.container.size();
}
public static void main(String[] args) {
StackTest<String> backHistory=new StackTest<String>(3);
backHistory.push("www.baidu.com");
backHistory.push("www.google.com");
backHistory.push("www.163.com");
backHistory.push("www.sina.com");
System.out.println(backHistory.size());
String item=null;
while (null!=(item=backHistory.pop())){
System.out.println(item);
}
}
}```