1 |
/* |
2 |
* @test %I% %E% |
3 |
* @bug 4486658 |
4 |
* @summary Checks that a priority queue returns elements in sorted order across various operations |
5 |
*/ |
6 |
|
7 |
import java.util.*; |
8 |
|
9 |
public class PriorityQueueSort { |
10 |
|
11 |
static class MyComparator implements Comparator<Integer> { |
12 |
public int compare(Integer x, Integer y) { |
13 |
int i = x.intValue(); |
14 |
int j = y.intValue(); |
15 |
if (i < j) return -1; |
16 |
if (i > j) return 1; |
17 |
return 0; |
18 |
} |
19 |
} |
20 |
|
21 |
public static void main(String[] args) { |
22 |
int n = 10000; |
23 |
if (args.length > 0) |
24 |
n = Integer.parseInt(args[0]); |
25 |
|
26 |
List<Integer> sorted = new ArrayList<Integer>(n); |
27 |
for (int i = 0; i < n; i++) |
28 |
sorted.add(new Integer(i)); |
29 |
List<Integer> shuffled = new ArrayList<Integer>(sorted); |
30 |
Collections.shuffle(shuffled); |
31 |
|
32 |
Queue<Integer> pq = new PriorityQueue<Integer>(n, new MyComparator()); |
33 |
for (Iterator<Integer> i = shuffled.iterator(); i.hasNext(); ) |
34 |
pq.add(i.next()); |
35 |
|
36 |
List<Integer> recons = new ArrayList<Integer>(); |
37 |
while (!pq.isEmpty()) |
38 |
recons.add(pq.remove()); |
39 |
if (!recons.equals(sorted)) |
40 |
throw new RuntimeException("Sort test failed"); |
41 |
|
42 |
recons.clear(); |
43 |
pq = new PriorityQueue<Integer>(shuffled); |
44 |
while (!pq.isEmpty()) |
45 |
recons.add(pq.remove()); |
46 |
if (!recons.equals(sorted)) |
47 |
throw new RuntimeException("Sort test failed"); |
48 |
|
49 |
// Remove all odd elements from queue |
50 |
pq = new PriorityQueue<Integer>(shuffled); |
51 |
for (Iterator<Integer> i = pq.iterator(); i.hasNext(); ) |
52 |
if ((i.next().intValue() & 1) == 1) |
53 |
i.remove(); |
54 |
recons.clear(); |
55 |
while (!pq.isEmpty()) |
56 |
recons.add(pq.remove()); |
57 |
|
58 |
for (Iterator<Integer> i = sorted.iterator(); i.hasNext(); ) |
59 |
if ((i.next().intValue() & 1) == 1) |
60 |
i.remove(); |
61 |
|
62 |
if (!recons.equals(sorted)) |
63 |
throw new RuntimeException("Iterator remove test failed."); |
64 |
} |
65 |
} |
66 |
|