接口Queue
数据结构,是Collenction,是队列数据结构
队列;通常一端进(offer),一端出(poll)
先进先出 FIFO
使用Linkedlist实现Queue接口,因为队列要增删
常用方法;
boolean offer(E e):从队尾进入队列
E poll():从队首删除 返回被移除元素,当队列没有元素时,返回null
E peek():查看队首元素,不移除,队列没有元素,则返回null
PS:为避免移除队首时出现null,最好先查看队首是否为null
例: /*定义一个队列,存储10个人*/
Queue<Person> queue = new LinkedList<Person>();
queue.offer(new Person("A",16));
queue.offer(new Person("B",46));
for(int i = 0;i<8;i++){
queue.offer(new Person("小"+(char)(i+67),i+10));
}
System.out.println(queue);//[(A,16), (B,46), (小C,10), (小D,11), (小E,12), (小F,13), (小G,14), (小H,15), (小I,16), (小J,17)]
/*打完饭,第一个人出队列*/
Person p1 = queue.poll();//出(先进先出)
System.out.println(p1);//(A,16)
System.out.println(queue);//[(B,46), (小C,10), (小D,11), (小E,12), (小F,13), (小G,14), (小H,15), (小I,16), (小J,17)]
/*查看队首是谁*/
Person p2 = queue.peek();//查看队首元素
System.out.println(p2);//(B,46)
System.out.println(queue);//[(B,46), (小C,10), (小D,11), (小E,12), (小F,13), (小G,14), (小H,15), (小I,16), (小J,17)]
Deque(数据结构):
Queue子接口,实现双端队列
双端队列:两端都可进可处
进带参,出带返回值
boolean offerFirst(E e)://队首进 返回值为E的意思是进去之后再把返回值引用
boolean offerLast(E e):
E pollFirst();//队首出
E pollLast();
E peekFirst();//队首查看
E peekLast();
例: Deque<Person> deque = new LinkedList<Person>();
/*从队首进*/
deque.offerFirst(new Person("小A",12));
deque.offerFirst(new Person("小B",14));
System.out.println(deque);
/*从队尾进*/
deque.offerLast(new Person("小C",20));
deque.offerLast(new Person("小D",25));
System.out.println(deque);
/*从队尾出*/
Person p1 = deque.pollLast();
System.out.println(p1);
System.out.println(deque);
/*从队首出*/
Person p2 = deque.pollFirst();
System.out.println(p2);
System.out.println(deque);
Person p3 = deque.poll();
System.out.println(p3);
System.out.println(deque);