Dr. Avinash Gautam CSIS, BITS Pilani: Java Collection Framework: Maps and Sets
Dr. Avinash Gautam CSIS, BITS Pilani: Java Collection Framework: Maps and Sets
1
Lists, revisited
Lists are slow for searching
indexOf, contains are slow (O(n))
must potentially look at each element of list
3
Set implementations in Java
Set is an interface; you can't say new Set()
There are two implementations:
java.util.HashSet is best for most purposes
we won't use the other one: TreeSet
Java's set implementations have been optimized so
that it is very fast to search for elements in them
contains method runs in constant time!
5
Typical set operations
Sometimes it is useful to compare sets:
subset: S1 is a subset of S2 if S2 contains every element
from S1.
11
Map implementations in Java
Map is an interface; you can't say new Map()
There are two implementations:
java.util.HashMap is best for most purposes
we won't use the other one: TreeMap
12
HashMap example
HashMap grades
HashMap grades = new HashMap();
grades.put("Martin", "A");
grades.put("Nelson", "F"); HashMapEntry
grades.put("Milhouse", "B");
grades.put("Nelson", "W");
2 "Nelson" "F"
grades.remove("Martin");
HashMapEntry
System.out.println(
grades.get("Nelson"));
System.out.println(
grades.get("Martin")); 5 "Milhouse" "B"
13
Map example
public class Birthday {
public static void main(String[] args){
Map m = new HashMap();
m.put("Newton", new Integer(1642));
m.put("Darwin", new Integer(1809));
System.out.println(m);
}
}
Output:
{Darwin=1809, Newton=1642}
14
Some Map methods in detail
public Object get(Object key)
returns the value at the specified key, or null if the key is
not in the map
public boolean containsKey(Object key)
returns true if the map contains a mapping for the
specified key
public boolean containsValue(Object val)
returns true if the map contains the specified object as a
value
15
Collection views
A map itself is not regarded as a collection
Map does not implement Collection interface
although, in theory, it could be seen as a collection
of pairs
16
Iterators and Maps
Map interface has no iterator method; you can’t get an Iterator
directly
Output:
Darwin => 1809
Newton => 1642
18
References
The Java Tutorial: Collections.
http://java.sun.com/docs/books/tutorial/
collections/index.html
19