Java Reference
In-Depth Information
1
// Fig. 16.15: PriorityQueueTest.java
2
// PriorityQueue test program.
3
import java.util.PriorityQueue;
4
5
public class PriorityQueueTest
6
{
7
public static void main(String[] args)
8
{
9
// queue of capacity 11
PriorityQueue<Double> queue = new PriorityQueue<>();
10
11
12
// insert elements to queue
queue.offer( 3.2) ;
queue.offer( 9.8 );
queue.offer( 5.4 );
13
14
15
16
17
System.out.print( "Polling from queue: " );
18
19
// display elements in queue
20
while (
queue.size()
> 0 )
21
{
22
System.out.printf( "%.1f " ,
queue.peek()
); // view top element
23
queue.poll();
// remove top element
24
}
25
}
26
} // end class PriorityQueueTest
Polling from queue: 3.2 5.4 9.8
Fig. 16.15 | PriorityQueue test program.
16.10 Sets
A Set is an unordered Collection of unique elements (i.e., no duplicates ). The collections
framework contains several Set implementations, including HashSet and TreeSet . Hash-
Set stores its elements in a hash table , and TreeSet stores its elements in a tree . Hash tables
are presented in Section 16.11. Trees are discussed in Section 21.7.
Figure 16.16 uses a HashSet to remove duplicate strings from a List . Recall that both
List and Collection are generic types, so line 16 creates a List that contains String
objects, and line 20 passes a Collection of String s to method printNonDuplicates .
Method printNonDuplicates (lines 24-35) takes a Collection argument. Line 27 con-
structs a HashSet<String> from the Collection<String> argument. By definition, Set s
do not contain duplicates, so when the HashSet is constructed, it removes any duplicates in
the Collection . Lines 31-32 output elements in the Set .
1
// Fig. 16.16: SetTest.java
2
// HashSet used to remove duplicate values from array of strings.
3
import java.util.List;
4
import java.util.Arrays;
Fig. 16.16 | HashSet used to remove duplicate values from an array of strings. (Part 1 of 2.)
 
 
Search WWH ::




Custom Search