Java Reference
In-Depth Information
This map works a bit more efficiently than the current default, but at the expense of having more unoc-
cupied space. When 90 objects have been stored, the capacity is increased to 303, (2 ×151 + 1).
Storing, Retrieving, and Removing Objects
Storing, retrieving, and removing objects in a
HashMap<>
is very simple. The methods involved in these op-
erations are the following:
•
V put(K key, V value)
: Stores the object
value
in the map using the key specified by the first
argument.
value
replaces any existing object associated with
key
, and a reference to the previous
object for the key is returned. If no object was previously stored for
key
or the key was used to
store
null
as an object,
null
is returned.
•
void putAll(Map<? extends K,? extends V> map)
: Transfers all the key/object pairs from
map
to the current map, replacing any objects that exist with the same keys.
•
V get(Object key)
: Returns the object stored with the same key as the argument. If no object
was stored with this key or
null
was stored as the object,
null
is returned. Note that the object
remains in the map.
•
V remove(Object key)
: Removes the entry associated with
key
if it exists and returns a reference
to the object. A
null
is returned if the entry does not exist, or if
null
was stored using
key
.
If you attempt to retrieve an object using
get()
and a
null
is returned, it is still possible that a
null
was
stored as the object associated with the key that you supplied to the
get()
method. You can determine if this
is the case by passing your key object to the
containsKey()
method for the map. This returns
true
if the
key is stored in the map.
You should ensure that the value returned from the
put()
method is
null
. If you don't, you may unwit-
tingly replace an object that was stored in the table earlier using the same key. The following code fragment
illustrates how you might do that:
HashMap<String,Integer> aMap = new HashMap<>();
String myKey = "Goofy";
int value = 12345;
Integer oldValue = null;
for (int i = 0 ; i < 4 ; ++i) {
if((oldValue = aMap.put(myKey, value++)) != null) {
System.out.println("Uh-oh, we bounced an object: " + oldValue);
}
}
Of course, you could throw your own exception here instead of displaying a message on the command line.
The second parameter to the
put()
method for the
aMap
object is of type
Integer
, so the compiler supplies
an autoboxing conversion for the
int
value that is passed as the argument.
If you execute this fragment, it generates the following output:
Uh-oh, we bounced an object: 12345
Uh-oh, we bounced an object: 12346
Uh-oh, we bounced an object: 12347
When the first value is stored, there's nothing stored in the map for the key, so there's no message. For
all subsequent attempts to store objects, the previous object is replaced, and a reference to it is returned.