

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. |
Map<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. |
The keys of a map form what kind of collection?
The values of a map form what kind of collection?
Suppose you want to implement a table of contents that shows the pages on which each particular word occurs. What is a good data structure for this purpose?
Object class has a hashCode methodequalsfinal 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 |
equalspublic 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;
}
}