19.9. Sets
A Set is a Collection that contains unique elements (i.e., no duplicate elements). 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. The concept of hash tables is presented in Section 19.10. Figure 19.18 uses a HashSet to remove duplicate strings from a List. Recall that both List and Collection are generic types, so line 18 creates a List that contains String objects, and line 24 passes a Collection of Strings to method printNonDuplicates.
Figure 19.18. HashSet used to remove duplicate values from array of strings.
1 // Fig. 19.18: SetTest.java 2 // Using a HashSet to remove duplicates. 3 import java.util.List; ... |
Get Java™ How to Program, Seventh Edition now with the O’Reilly learning platform.
O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.