interfaceQueue<E>{ voidadd(E element); E remove(); intsize(); }
| 1 | 2 | 3 | 4 | ↑ ↑ 队头 队尾
这个接口并没有说明队列是如何实现的。队列实现有两种方式:循环数组、链表。
循环数组实现:
1 2 3 4 5 6 7 8 9
classCircularArrayQueue<E> implementsQueue<E>{ CircularArrayQueue(int capacity){...} publicvoidadd(E element){...} public E remove(){...} publicintsize(){...} private E[] elements; privateint head; private tail; }
链表实现:
1 2 3 4 5 6 7 8 9
classLinkedListQueue<E> implementsQueue<E>{ LinkedListQueue(){...} publicvoidadd(E element){...} public E reove(){...} publicintsize(){...} private Link head; private Link tail; }
完全解耦
为了解释接口的解耦功能,我们先引入一个例子:
程序员甲写了一个Node1,并且写了一个两个Node1的排序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicclassNode1{ int val; int count; publicintCompareTo(Node1 o){ returnthis.val - o.val; } } publicstatic Node1[] sort(Node1 a,Node1 b){ if( a.CompareTo(b) > 0 ){ returnnew Node1[]{a,b}; }else{ returnnew Node1[]{b,a}; } } publicstaticvoidmain(String[] args){ Node1 a = new Node1();//此处省略 Node1 b = new Node1(); sort(a,b); }
程序员乙写了一个Node2,也写了一个两个Node2的排序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicclassNode2{ String key; int val; publicintCompareTo(Node2 o){ returnthis.val - o.val; } } publicstatic Node2[] sort(Node2 a,Node2 b){ if( a.CompareTo(b) > 0 ){ returnnew Node2[]{a,b}; }else{ returnnew Node2[]{b,a}; } } publicstaticvoidmain(String[] args){ Node2 a = new Node2();//此处省略 Node2 b = new Node2(); sort(a,b); }