Set
Set<String> names = new HashSet<>(); Set<String> names = new TreeSet<>(); Set<String> names = new TreeSet<>(myComparator);
Set<String> names; |
Use the interface type for variable declarations |
names = new HashSet<>(); |
Use a TreeSet if you need to visit the elements in sorted order. |
names.add("Romeo"); |
Now names.size() is 1 |
names.add("Fred"); |
Now names.size() is 2 |
names.add("Romeo"); |
names.size() is still 2. You can’t add duplicates. |
if (names.contains("Fred")) |
The contains method checks whether a value is contained in the set. In this case, the method returns true . |
System.out.println(names); |
Prints the set in the format [Fred, Romeo] . The elements need not be shown in the order in which they were inserted. |
for (String name : names) {...} |
Use this loop to visit all elements of a set. (You can also use an iterator.) |
names.remove("Romeo"); |
Now names.size() is 1 |
names.remove("Juliet"); |
It is not an error to remove an element that is not present. The method call has no effect. |
names.removeIf(s -> s.startsWith("R")); |
Removes all elements that fulfill the predicate. |
How many unique words are there in "Alice in Wonderland", if you ignore letter case?
Complete this program.
Try to implement this method with the minimum amount of work.
What did you do?
for
each” loopsSet
interface, without any loopsTry to implement this method with the minimum amount of work.
What did you do?
for
each” loopsSet
interface, without any loopsMap<String, Color>
HashMap
and TreeMap
implementationsTreeMap
visits the keys in sorted order
Map<String, Integer> scores; |
Keys are strings, values are Integer wrappers. Use the interface type for variable declarations. |
scores = new TreeMap<>(); |
Use a HashMap if you don’t need to visit the keys in sorted order. |
scores.put("Harry", 90); scores.put("Sally", 95); |
Adds keys and values to the map. |
scores.put("Sally", 100); |
Modifies the value of an existing key. |
int n = scores.get("Sally"); |
Gets the value associated with a key, or null if the key is not present. n is 100, n2 is null. |
System.out.println(scores); |
Prints scores.toString(), a string of the form {Harry=90, Sally=100} |
for (String key : scores.keySet()) |
Iterates through all map keys and values. |
scores.remove("Sally"); |
Removes the key and value. |
We want to count how many words have length 1, length 2, and so on.
Complete this program.
How many words have length 10?
Object
class has a hashCode
methodequals
final int HASH_MULTIPLIER = 31; int h = 0; for (int i = 0; i < s.length(); i++) h = HASH_MULTIPLIER * h + s.charAt(i);
eat | 100184 = 31 * (31 * 'e' + 'a') + 't' |
tea | 114704 |
Juliet | –2065036585 |
Ugh | 84982 |
VII | 84982 |
equals
public class Country { public int hashCode() { int h1 = name.hashCode(); int h2 = new Double(area).hashCode(); final int HASH_MULTIPLIER = 31; int h = HASH_MULTIPLIER * h1 + h2; return h; } }
What is the hash code of the string "d¢"
?
(Hint: Appendix 1 of your text book)