Start learning free

LESSON 230 OF 671 · SETS

Sets in Java

Lesson

TL ; DR:

A HashSet holds values without repeats. Adding a value that is already in it changes nothing.


HashSet<String> pets = new HashSet<>(List.of("cat", "dog", "cat"));   // cat goes in once

pets.add("fish");                            // a new value

pets.add("dog");                             // already in it, no change

System.out.println(pets.size());             // 3

System.out.println(pets.contains("dog"));    // true


Full lesson:

An ArrayList keeps every value you put in it, repeats too. Sometimes you only need to know which values there are. A set is made for that.

A set holds each value once. Adding a value that is already in it changes nothing.

  • new HashSet<>() makes an empty set. A set of strings has the type HashSet<String>.
  • s.add(x) puts x in the set s.
  • s.contains(x) is true when x is in the set.
  • s.size() gives how many values the set holds.
  • new HashSet<>(list) builds a set from a list. Its repeats go in once.

Checking s.contains(x) is fast, even for a big set. A list's contains looks at the values one by one.

Like a HashMap, a HashSet holds objects. A set of numbers is a HashSet<Integer>, never HashSet<int>.

A set has no order and no indexes. It has no get(i). A printed set may show its values in any order.


Your task

The camp's sign-up list, names, has some names twice. Build a HashSet named kids from it.

Then Zoe signs up, and Ava signs up again. Add both names to kids.

Last, if kids contains "Leo", print Leo is coming.

The code already prints the number of kids twice.

Expected output:

3 kids
4 kids
Leo is coming
STEP 1 OF 3
    Ctrl + Enter to check