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