The HashSet
and HashMap
classes are implementations of the Set
and Map
interfaces from the Java standard class Library. A hash table is used to store their elements.
The methods from the HashSet
and HashMap
that are included in the AP Subset are shown below:
Methods of the HashSet Class included in the AP Subset*
// Adds the specified element to this set if it is not
// already present. Returns true if the set did not already
// contain the specified element.
boolean add(Object obj);
// Returns true if this set contains the specified element.
boolean contains(Object obj);
// Returns an iterator over the elements in this set.
// The elements are returned in no particular order.
Iterator iterator()
// Removes the specified element from this set if it is
// present. Returns true if the set contained the specified
// element.
boolean remove(Object obj);
// Returns the number of elements in this set.
int size();
Methods of the HashMap Class included in the AP Subset*
// Returns true if this map contains a mapping for the
// specified key.
boolean containsKey(Object key);
// Returns the value to which the specified key is mapped,
// or null if the map contains no mapping for this key.
Object get(Object key);
// Returns a set containing the keys in this map.
Set keySet()
// Adds the key-value pair to this map. Returns the previous
// value associated with specified key, or null if there was
// no mapping for key.
Object put(Object key, Object value);
// Returns the number of key-value pairs in this map.
int size();
In the HashSet
class, a hash of the elements is used to find its location in the
hash table. Whenever you use a hash set, you need to make sure that an appropriate hash function exists for the type of objects that you add to the set.
When you use a HashMap
only the keys are hashed. They need compatible hashCode
and equals
methods. The values are never hashed or compared since the map only needs to find, add, and remove keys quickly.
The basic operations on HashSet
and HashMap
objects run in constant, O(1)
, time due to the hash table implementation employed by the class.
-
The iterator that is returned by the iterator
method of HashSet
does not order the objects returned.