Given:
1. import java.util.*; 2. public class Main { 3. public static void main(String[] args) { 4. PriorityQueue<String> pq = new PriorityQueue<String>(); 5. pq.add("4"); 6. pq.add("7"); 7. pq.add("2"); 8. // insert code here 9. } }
Which code fragment(s), inserted independently at line 8, produce the output "2-4-7-"?
(Choose all that apply.)
A. Iterator it2 = pq.iterator(); while(it2.hasNext()) System.out.print(it2.next() + "-"); System.out.println(); //from w w w. j a v a 2 s.c o m B. Arrays.sort(pq.toArray()); Iterator it3 = pq.iterator(); while(it3.hasNext()) System.out.print(it3.next() + "-"); System.out.println(); C. Object[] pqa = pq.toArray(); Arrays.sort(pqa); for(Object o: pqa) System.out.print(o + "-"); System.out.println(); D. String s = pq.poll(); while (s != null) { System.out.print(s + "-"); s = pq.poll(); } E. String s = pq.peek(); while (s != null) { System.out.print(s + "-"); s = pq.peek(); }
C and D
C and D are correct ways to determine how elements in the PriorityQueue would be prioritized, although D consumes the queue in the process.
A is incorrect because the Iterator for PriorityQueue does NOT guarantee a sorted result.
B is incorrect because the toArray()
method creates a new array, it doesn't change the existing array.
E is incorrect because peek()
only looks at a queue's "first" element, it doesn't consume it, so an infinite loop is created.
Note: If you didn't get answer A that's okay.
Answer A might be a little bit on the trivia end of the spectrum.
So if you got this question correct except for answer A, give yourself full credit.