java · level 2 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A keeps each value once and ignores duplicates.
A HashSet is a bag that refuses a . .add("red") puts red in. Add red again and nothing changes: .add gives back false to say it was already there.
Sets are fast at one question: is this in here? .contains answers it, and .size() counts the different values. A HashSet has no index and no order, so reach for a when you want the values sorted.
To clean the repeats out of a list, pour it into a set: new TreeSet<>(stamps).
import java.util.*;
public class Main {
public static void main(String[] args) {
HashSet<String> colours = new HashSet<>();
System.out.println(colours.add("red"));
System.out.println(colours.add("blue"));
System.out.println(colours.add("red"));
System.out.println(colours.size() + " " + colours.contains("blue"));
List<String> stamps = List.of("UK", "France", "UK", "Spain", "France");
System.out.println(new TreeSet<>(stamps));
}
} Use a list when order or repeats matter, and a set when they do not.
guess first
Visitors sign the guest book. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] visits = {"Sam", "Ali", "Sam", "Jo", "Ali", "Sam"};
HashSet<String> visitors = new HashSet<>();
for (String name : visits) {
visitors.add(name);
}
System.out.println(visits.length + " visits, " + visitors.size() + " visitors");
}
}
your turn
Your turn. Play the word game.
Type a word between the quotes on line 5. Try a new word, then try apple. Press run each time to see the sorted set.
output
press run to see what happens
fix it
The badge count has repeats. Fix it!
output
press run to see what happens
- It counts 4 badges, but swimming is there twice. Which kind of collection keeps repeats?
- A list keeps every item, repeats included. A set keeps each value once.
- Change line 5 to
HashSet<String> badges = new HashSet<>();, then press run.
nailed it
you banished the duplicates. :D
- A
HashSetkeeps each value only once. .addgivesfalsewhen the value was already there.- Pour a list into a
TreeSetfor sorted values with no repeats.
new words in your collection
- HashSet
- duplicate
- TreeSet
This lesson isn’t saved. A free account remembers every lesson you finish.