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. HashSet 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 Strings to method printNonDuplicates. Method printNonDuplicates (lines 24–35) takes a Collection argument. Line 27 constructs a HashSet<String> from the Collection<String> argument. By ...

Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.