Queue 的 Array 實作..因為 Array 在 Java 中是使用固定的形式 所以引致了 toString 排序時候出現了兩種可能性..
是正常的情況..”前者比後者小”..
是由於固定情況.所以如果資料多了就會在 0 的位置再次填上.
– 這樣會引致了 “後者比前者小”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 class ArrayQueue { private int size, head, tail, count; private Object data[]; public ArrayQueue (int size) { this .size = size; this .data = new Object[this .size]; this .head = 0 ; this .count = 0 ; this .tail = -1 ; } public boolean full () { return this .count == this .size; } public boolean empty () { return this .count <= 0 ; } public void enqueue (Object item) throws QueueFullException { if (this .full()) throw new QueueFullException(); this .count++; if (this .tail < this .size - 1 ) { this .tail++; }else { this .tail = 0 ; } this .data[this .tail] = item; } public Object dequeue () throws EmptyQueueException { if (this .empty()) throw new EmptyQueueException(); this .count--; Object item = this .data[this .head]; if (this .head < this .size - 1 ) { this .head++; }else { this .head = 0 ; } return item; } public String toString () { String str = "[ " ; if (this .empty()) return str + "]" ; if (this .tail >= this .head && this .tail < this .size) { for (int i=this .head; i<=this .tail; i++) { str += data[i] + " " ; } } if (this .tail < this .head) { for (int i=this .head; i<this .size; i++) { str += data[i] + " " ; } for (int i=0 ; i<=this .tail; i++) { str += data[i] + " " ; } } return str + "]" ; } } class EmptyQueueException extends RuntimeException { public EmptyQueueException () { super ("Queue Is Empty" ); } } class QueueFullException extends RuntimeException { public QueueFullException () { super ("Queue Is Full" ); } }
經過高人指點後..得到的新方法?
1 2 3 4 5 6 7 8 9 10 11 12 13 public String toString () { String s = "Head [ " ; int index = this .head; for (int i = 0 ; i < this .count; i++) { s = s + entry[index] + " " ; if (index < this .size - 1 ) index++; else index = 0 ; } s = s + "] Tail" ; return s; }