J.8. Sets

A Set is an unordered Collection of 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. Hash tables are presented in Section J.9.

Figure J.8 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.

 1   // Fig. J.8: SetTest.java 2   // HashSet used to remove duplicate values from an array of strings. 3   import java.util.List; 4   import java.util.Arrays; ...

Get Android™ How to Program, Second 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.