CS 46B - Lecture 14

Cover page image

Pre-class reading

Sets

..

Constructing Sets

Working with Sets

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.

Maps

.

Working with maps

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");
Integer n2 = scores.get("Diana");
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())
{
Integer value = scores.get(key);
. . .
}
Iterates through all map keys and values.
scores.remove("Sally"); Removes the key and value.

Lecture 14 Clicker Question 1

The keys of a map form what kind of collection?

  1. A set
  2. A stack
  3. A list
  4. None of the above

Lecture 14 Clicker Question 2

The values of a map form what kind of collection?

  1. A set
  2. A stack
  3. A list
  4. None of the above

Lecture 14 Clicker Question 3

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?

  1. TreeMap<Integer, TreeSet<String>>
  2. TreeMap<String, TreeSet<Integer>>
  3. TreeSet<TreeMap<String, Integer>>
  4. TreeSet<TreeMap<Integer, String>>

Hash Functions

Example: Hash code for String

final int HASH_MULTIPLIER = 31;
int h = 0;
for (int i = 0; i < s.length(); i++)
   h = HASH_MULTIPLIER * h + s.charAt(i);  
eat100184 = 31 * (31 * 'e' + 'a') + 't'
tea114704
Juliet–2065036585
Ugh84982
VII84982

Implementing Hash Functions

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;
   }
}