1.队列:
除啦一些并发队列,队列在集合中的实现有LinkedList和PriorityQueue两种<br />
public class QueueBehavior {
private static int count=10;
static <T> void test(Queue<T> queue, Gererator<T> gen) {
for (int i = 0; i <count ; i++) {
queue.offer(gen.next());
}
while(queue.peek()!=null){
System.out.print(queue.remove()+" ");
}
System.out.println();
}
static class Gen implements Gererator<String>{
String [] s=("one two three four five six seven "+"eight nine ten").split(" ");
int i;
@Override
public String next() {
return s[i++];
}
}
public static void main(String[] args) {
test(new LinkedList<String>(),new Gen());
test(new PriorityQueue<String>(),new Gen());
//以下是并发队列
test(new ArrayBlockingQueue<String>(count),new Gen());
test(new ConcurrentLinkedQueue<String>(),new Gen());
test(new LinkedBlockingDeque<String>(),new Gen());
test(new PriorityBlockingQueue<String>(),new Gen());
}
}
2.优先队列
优先队列中最有器的是todo列表,该列表的每个对象都包含一个字符串和一个主要的以及次要的优先值。该列表的顺序也是通过实现Comparable而进行控制
public class TodList extends PriorityQueue<TodList.ToDoItem> {
static class ToDoItem implements Comparable<ToDoItem> {
private char primary;
private int secondary;
private String item;
public ToDoItem(String td, char pri, int sec) {
primary = pri;
item = td;
secondary = sec;
}
public int compareTo(ToDoItem arg) {
if (primary > arg.primary)
return +1;
if (primary == arg.primary)
if (secondary > arg.secondary)
return +1;
else if (secondary == arg.secondary)
return 0;
return -1;
}
@Override
public String toString() {
return Character.toString(primary)+secondary+":"+item;
}
}
public void add(String td,char pri,int sec){
super.add(new ToDoItem(td, pri, sec));
}
public static void main(String[] args) {
final TodList toDoItems = new TodList();
toDoItems.add("Empy trash",'C',4);
while (!toDoItems.isEmpty()){
System.out.println(toDoItems.remove());
}
}
}
<br />3.双向队列(Deque):<br /> 双向队列Deque,使你可以在队列的两端都可以添加或移除元素,Linkedist中包含支持双向队列的方法,因此可以使用LinkedList来组合来创建一个Deque类<br /> 示列,LinkedList组合Deque
public class Deque<T> {
private LinkedList<T> deque = new LinkedList<T>();
public void addFirst(T e) { deque.addFirst(e); }
public void addLast(T e) { deque.addLast(e); }
public T getFirst() { return deque.getFirst(); }
public T getLast() { return deque.getLast(); }
public T removeFirst() { return deque.removeFirst(); }
public T removeLast() { return deque.removeLast(); }
public int size() { return deque.size(); }
public String toString() { return deque.toString(); }
测试:
public class DequeTest {
static void fillTest(Deque<Integer> deque) {
for (int i = 20; i < 27; i++)
deque.addFirst(i);
for (int i = 50; i < 55; i++)
deque.addLast(i);
}
public static void main(String[] args) {
Deque<Integer> di = new Deque<Integer>();
ArrayDeque<Integer> d=new ArrayDeque<>();
fillTest(di);
System.out.println(di);
while (di.size() != 0)
System.out.println(di.removeFirst() + " ");
System.out.println();
fillTest(di);
while (di.size() != 0)
System.out.println(di.removeLast() + " ");
}
}