Queue在java中的实现只有LinkedList和PriorityQueue
大部分的操作都在这?
(bruce的例子总是很长很繁琐…只看*就行)
//: containers/QueueBehavior.java
// Compares the behavior of some of the queues
import java.util.concurrent.*;
import java.util.*;
import net.mindview.util.*;
public class QueueBehavior {
private static int count = 10;
static <T> void test(Queue<T> queue, Generator<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 Generator<String> {
String[] s = ("one two three four five six seven " +
"eight nine ten").split(" ");
int i;
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 LinkedBlockingQueue<String>(), new Gen());
test(new PriorityBlockingQueue<String>(), new Gen());
}
} /* Output:
one two three four five six seven eight nine ten //链表
eight five four nine one seven six ten three two //优先队列
one two three four five six seven eight nine ten //ArrayBlockingQueue
one two three four five six seven eight nine ten //ConcurrentLinkedQueue
one two three four five six seven eight nine ten //LinkedBlockingQueue
eight five four nine one seven six ten three two //PriorityBlockingQueue
*///:~
priorityQueue
看看里面怎么写比较方法compareTo的就好
import java.util.*;
class ToDoList extends PriorityQueue<ToDoList.ToDoItem> {
//内部类:ToDoList 并实现了接口comparable
static class ToDoItem implements Comparable<ToDoItem> {
private char primary;
private int secondary;
private String item;
//constructor
public ToDoItem(String td, char pri, int sec) {
primary = pri;
secondary = sec;
item = td;
}
//*厉害的地方来了 */
//是comparable接口里面的方法
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;
}
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) {
//这里只是举例不看了不看了
ToDoList toDoList = new ToDoList();
toDoList.add("Empty trash", ‘C’, 4);
toDoList.add("Feed dog", ‘A’, 2);
toDoList.add("Feed bird", ‘B’, 7);
toDoList.add("Mow lawn", ‘C’, 3);
toDoList.add("Water lawn", ‘A’, 1);
toDoList.add("Feed cat", ‘B’, 1);
while(!toDoList.isEmpty())
System.out.println(toDoList.remove());
}
} /* Output:
A1: Water lawn
A2: Feed dog
B1: Feed cat
B7: Feed bird
C3: Mow lawn
C4: Empty trash
*///:~
Deque
上面就是自己实现了一个类,感觉没什么用的亚子(小声