Task 3 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 — add tells you if it was new

Lesson

Was it already there?

add returns a boolean: true if the value was new (actually added), or false if it was already in the set. This is handy for detecting duplicates as you go — if add returns false, you have seen that value before.


Worked example

Set<Integer> nums = new HashSet<Integer>();
System.out.println(nums.add(5));   // true — new
System.out.println(nums.add(5));   // false — already present
System.out.println(nums.add(7));   // true — new
System.out.println(nums.size());   // 2

A false from add is a signal that the value is a repeat.


▶ Try it: run this — watch which adds report new (true) versus repeat (false).



add(value) returns...


If add(x) returns false, then...


Type exactly what this program prints.

import java.util.HashSet;
import java.util.Set;
public class Main { public static void main(String[] a){
    Set<Integer> s = new HashSet<Integer>();
    System.out.println(s.add(3));
    System.out.println(s.add(4));
    System.out.println(s.add(3));
}}

You can detect a duplicate while inserting by checking...


True or false?