📅  最后修改于: 2020-10-12 10:00:35             🧑  作者: Mango
Java Deque接口是一个线性集合,支持两端的元素插入和删除。 Deque是“双头队列”的缩写。
public interface Deque extends Queue
Method | Description |
---|---|
boolean add(object) | It is used to insert the specified element into this deque and return true upon success. |
boolean offer(object) | It is used to insert the specified element into this deque. |
Object remove() | It is used to retrieves and removes the head of this deque. |
Object poll() | It is used to retrieves and removes the head of this deque, or returns null if this deque is empty. |
Object element() | It is used to retrieves, but does not remove, the head of this deque. |
Object peek() | It is used to retrieves, but does not remove, the head of this deque, or returns null if this deque is empty. |
ArrayDeque类提供使用双端队列和可调整大小的数组的便利。它继承了AbstractCollection类并实现了Deque接口。
关于ArrayDeque类的要点是:
在页面右侧显示的图中给出了ArrayDeque类的层次结构。
我们来看一下java.util.ArrayDeque类的声明。
public class ArrayDeque extends AbstractCollection implements Deque, Cloneable, Serializable
import java.util.*;
public class ArrayDequeExample {
public static void main(String[] args) {
//Creating Deque and adding elements
Deque deque = new ArrayDeque();
deque.add("Ravi");
deque.add("Vijay");
deque.add("Ajay");
//Traversing elements
for (String str : deque) {
System.out.println(str);
}
}
}
输出:
Ravi
Vijay
Ajay
import java.util.*;
public class DequeExample {
public static void main(String[] args) {
Deque deque=new ArrayDeque();
deque.offer("arvind");
deque.offer("vimal");
deque.add("mukul");
deque.offerFirst("jai");
System.out.println("After offerFirst Traversal...");
for(String s:deque){
System.out.println(s);
}
//deque.poll();
//deque.pollFirst();//it is same as poll()
deque.pollLast();
System.out.println("After pollLast() Traversal...");
for(String s:deque){
System.out.println(s);
}
}
}
输出:
After offerFirst Traversal...
jai
arvind
vimal
mukul
After pollLast() Traversal...
jai
arvind
vimal
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class ArrayDequeExample {
public static void main(String[] args) {
Deque set=new ArrayDeque();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to Deque
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing ArrayDeque
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
输出:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6