方法实现:
//1.3.41 public Queue(Queue<Item> q) { Queue<Item> result = new Queue<Item>(); int size = q.size(); for(int i = 0; i < size; i++) { Item item= q.dequeue(); q.enqueue(item); result.enqueue(item); } this.first = result.first; this.last = result.last; this.n = result.size(); }
测试:
//1.3.41 Queue<String> r = new Queue<String>(queue); StdOut.println("After copy"); StdOut.print("Left on queue r: "); for (String s : r) { StdOut.print(s + " "); } StdOut.println(); StdOut.print("Left on queue queue: "); for (String s : queue) { StdOut.print(s + " "); } StdOut.println(); r.dequeue(); StdOut.println("After r.dequeue"); StdOut.print("Left on queue r: "); for (String s : r) { StdOut.print(s + " "); } StdOut.println(); StdOut.print("Left on queue queue: "); for (String s : queue) { StdOut.print(s + " "); } StdOut.println();
结果:
After copy
Left on queue r: to be or not
Left on queue queue: to be or not
After r.dequeue
Left on queue r: be or not
Left on queue queue: to be or not