11 using maps
TRANSCRIPT
-
8/6/2019 11 Using Maps
1/29
Using Maps
-
8/6/2019 11 Using Maps
2/29
2
A simple map: Hashtable
To create a Hashtable, use:import java.util.*;Hashtable table = new Hashtable();
To put things into a Hashtable, use:
table.put(key, value);
To retrieve a value from a Hashtable, use:value = table.get(key);
-
8/6/2019 11 Using Maps
3/29
3
Example use of a Hashtable
import java.util.*;
publicclass HashtableUser {
public static voidmain(String[] args) {
Hashtable table =new Hashtable();table.put("one", "un");table.put("two", "deux");table.put("three", "trois");System.out.println("two -> " + table.get("two"));
System.out.println("deux -> " + table.get("deux"));}}
two -> deuxdeux -> null
-
8/6/2019 11 Using Maps
4/29
4
Hashtable constructors
Hashtable()
Constructs a new, empty Hashtable with a default capacity(11) and default load factor(0.75).
Hashtable(int initialCapacity)
Constructs a new, empty Hashtable with the specified initialcapacity and the default load factor(0.75).
Hashtable(int initialCapacity, float loadFactor)
Constructs a new, empty Hashtable with the specified initial
capacity and the specified load factor. Hashtable(Mapt)
Constructs a new Hashtable with the same mappings as thegiven Map.
-
8/6/2019 11 Using Maps
5/29
5
Which constructor should you use?
This is basically a question of efficiency
A hash table that is mostly empty wastes space
If a hash table is nearly full, some searches may take a
very long time The initial capacity of a hash table is the number
of entries that it can hold initially
The load factoris a measure of how full it is
A load factorof 75% is usually a good compromise
If the table gets fuller than the load factor, Java creates
a new, larger hash table and rehashes everything
Rehashing is an expensive operation
-
8/6/2019 11 Using Maps
6/29
6
Hashtable constructors (again)
Hashtable()
Use if the default values are good enough
Hashtable(int initialCapacity)
Use if you have some idea how many entries to expect
Try to ensure it wont be more than 75% full
If space is not an issue, double or triple the size
Hashtable(int initialCapacity, float loadFactor)
Use if you are trying to be super efficient
Requires careful experimentation and tuning
Hashtable(Map
-
8/6/2019 11 Using Maps
7/29
7
The Collections framework
Hashtable is an old (pre-Collections) class
Hashtable has been retrofitted toimplement the Map
interface
Collection
SortedSet
ListSetSortedMap
Map
Hashtable
-
8/6/2019 11 Using Maps
8/29
8
The Map interface I
Basic operations: V put(K key, V value)
Returns the previous value associated with key, ornull if therewas no previous value
V get(Object key)
Returns null if the key was not found A return value ofnull may notmean the key was not found
(some implementations ofMap allow null keys and values)
Tests: boolean containsKey(Object key)
boolean containsValue(Object value) Warning:probably requires linear time!
boolean isEmpty()
boolean equals(Object o)
Returns true ifo is also a map and has the same mappings
-
8/6/2019 11 Using Maps
9/29
9
The Map interface II
Optional operations: V put(K key, V value)
(So you could implement an immutable map)
voidputAll(Mapt)
Adds the mappings from t to this map
voidclear()
Object remove(Object key)
Returns the value that was associated with the key, ornull
Other: int size()
Returns the numberof key-value mappings
int hashCode()
Returns a hash code value for this map
-
8/6/2019 11 Using Maps
10/29
10
Optional operations
Question: How can a method declared in an
interface be optional?
Answer: you have to implement it, but the
implementation may be something like this:public voidremove(Object key)
throws UnsupportedOperationException {throw new UnsupportedOperationException();
}
In fact, HashMap extends AbstractMap, whichprovides many of the map operations, and
implements the optional operations exactly this way
-
8/6/2019 11 Using Maps
11/29
11
Map views
Set keySet()
Returns a set view of the keys contained in this map.
Collection values()
Returns a collection view of the values contained in this map
Cant be a setkeys must be unique, but values may be repeated
Set entrySet() Returns a set view of the mappings contained in this map.
A view is dynamic access into the Map
If you change the Map, the view changes If you change the view, the Map changes
The Map interface does not provide any Iterators
However, there are iterators for the above Sets and Collections
-
8/6/2019 11 Using Maps
12/29
12
Map.Entry:
Interface forentrySet elements
publicinterface Entry {K getKey( );
V getValue( );V setValue(V value);
}
This is a small interface for working with the
Collection returned by entrySet( ) Can get elements only from the Iterator, and
they are only valid during the iteration
-
8/6/2019 11 Using Maps
13/29
13
Constructors
Map is an interface, so it cannot require any constructors
However, Java always supplies:
A no-argument constructor for each Map type
A constructor that takes a Map argument, and copies its key-value pairs into the new Map
If you ever implement yourown Map class, you should
define these constructors
Defining yourown Map class is easy:class MyMapimplements Map { ... }
There are, however, a lot of methods to implement
-
8/6/2019 11 Using Maps
14/29
14
Hazards I
In order for a Hashtable to work correctly,
equals must be defined properly on the keys
hashCode must be defined properly on the keys
This is not a problem if you use Strings for the keys (this isextremely common)
If you use objects of some other class as your keys, you must
make sure equals and hashCode are properly defined
Note: equals and hashCode are properly defined for all ofJavas Maps; its the eys that you need to be careful with
-
8/6/2019 11 Using Maps
15/29
-
8/6/2019 11 Using Maps
16/29
16
From Hashtables toHashMaps
Hashtable has been around a long time, but HashMapis new with Java 1.2
So why am I teaching you the old stuff?
Actually, except for the constructors, Ive been talking about
the Map interface, which both Hashtable and HashMapimplement
Both are cloneable (more on this later) and serializable
Differences:
Hashtable is synchronized; HashMap is not HashMappermits null values and (one) null key; Hashtable
does not
-
8/6/2019 11 Using Maps
17/29
17
synchronized
Java supports multiple Threads
AThread is an execution sequence
Having multiple Threads means that Java appears to be
doing many different things all at the same time
Threads can interfere with each other unless they are
carefully synchronized (prevented from both using the
same data at the same time)
This can be an issue with GUIs, which run in a different
Thread from the rest of the program If you use a hash table from an event handler, use a
Hashtable (which is synchronized) instead of a
HashMap (which is not)
-
8/6/2019 11 Using Maps
18/29
18
Copying objects
In Java, you seldom copy objects, you just copy
references toobjects
Person jack = john;
jack.name = "Jack";jack
Person mary = new Person("Mary", 21);
Person john = new
Person("John",
23, mary);mary.setSpouse(john);
"John"
23
john
"John"
21
"Mary"
Suppose, however, that you really do want to make a copy;how do you do it?
Answer: y
ou cl
one the
object
"Jack"
-
8/6/2019 11 Using Maps
19/29
-
8/6/2019 11 Using Maps
20/29
20
Copy constructors
Rather than use cloneable, its usually better to write a copyconstructora constructor that takes an object as a parameter and
makes anotherobject just like it
Example: Person jack = new Person(john);
There is nothing magic about a copy constructorits up to youto make a deep copy rather than a shallow copy
Person (Person original) {this.name = original.name;
this.spouse = new Person(original.spouse);this.spouse.spouse = this; // why?
}
Does this actually work?
-
8/6/2019 11 Using Maps
21/29
21
The SortedMap interface
A hash table keeps elements in an (apparently)random order
Sometimes you want the keys of a map to be in
sorted order(e.g. phone book, dictionary) A map can be implemented with a hash table, but
it doesnt have to be
T
heSortedMap
interface implements theMap
interface and provides additional methods
For efficiency, you want an implementation thatkeeps its elements in some kind oforder
-
8/6/2019 11 Using Maps
22/29
22
Requirements forSortedMap
ASortedMap keeps its elements in the orderof increasingkey values
Therefore, it must be possible tosort the keys!
This means: The keys must be objects of a type that implement the
Comparable interface (or be given a Comparator)
Keys must be mutually comparable (e.g. you cant compare aString to a Button)
The ordering must be consistent with equals
All implementations ofSortedMap should supply fourconstructors
Well see an example of these shortly
-
8/6/2019 11 Using Maps
23/29
23
SortedMap Methods I
Comparator
-
8/6/2019 11 Using Maps
24/29
-
8/6/2019 11 Using Maps
25/29
25
The TreeMap class
TreeMap implements SortedMap
TreeMap is the only implementation that Java provides
forSortedMap
Question: Since theres only one implementation, whybother to have a separate interface?
Answer: To give you the flexibility to define additional
kinds of sorted map, if you wish to
You probably wontbut the flexibility is there
-
8/6/2019 11 Using Maps
26/29
26
TreeMap constructors
TreeMap()
Constructs a new, empty map, sorted according to the keys' natural order.
TreeMap(Comparator
-
8/6/2019 11 Using Maps
27/29
27
Quick summary
Interfaces (cannot instantiate):
Map
SortedMap
Serializable
Cloneable
Classes (can instantiate):
Hashtable
HashMap
TreeMap
As always, its best to avoid exposing the implementation; hence: Map myMap = new HashMap();
But probably not:
Map myMap = new TreeMap();
-
8/6/2019 11 Using Maps
28/29
28
Sets
Weve talked about Sets before, and you probablyremember the basic operations: int size( );
boolean isEmpty( );boolean contains(Object e);boolean add(E e);boolean remove(Object e);Iterator iterator( );
However, Set is an interface, not a class
There are two supplied implementations: HashSet(for when you dont care about the orderof
elements) and TreeSet (for when you do)
-
8/6/2019 11 Using Maps
29/29
29
The End