Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

10.2 HashSet — a collection of unique values

Lesson

No duplicates allowed

A HashSet stores a collection of unique values — no duplicates. Written Set<E>, it is generic in the element type. Use add(value) to insert, contains(value) to test membership, and size() for the count. Adding a value that is already in the set simply does nothing — the set still holds one copy.


Worked example

Set<String> seen = new HashSet<String>();
seen.add("Ada");
seen.add("Sam");
seen.add("Ada");                        // duplicate — ignored
System.out.println(seen.contains("Ada"));   // true
System.out.println(seen.contains("Bo"));    // false
System.out.println(seen.size());            // 2, not 3

Even though add("Ada") was called twice, the set holds "Ada" once.


▶ Try it: run this — the duplicate add does not change the size.



A HashSet stores...


Adding a value that is already in the set...


Type exactly what this program prints.

import java.util.HashSet;
import java.util.Set;
public class Main { public static void main(String[] a){
    Set<String> s = new HashSet<String>();
    s.add("x");
    s.add("y");
    s.add("x");
    s.add("z");
    System.out.println(s.size());
    System.out.println(s.contains("y"));
}}

To test whether a value is in the set, use...


True or false?