Java Reference
In-Depth Information
The comparison operations methods deal with comparing two
Map
s for equality. Examples of methods in this
category are as follows:
•
boolean equals (Object o)
int hashCode()
The
HashMap
,
LinkedHashMap
, and
WeakHashMap
are three of the available implementation classes
for the
Map
interface.
The
HashMap
allows one
null
value as a key and multiple
null
values as the values. The following snippet of code
demonstrates how to create and use a
Map
. A
HashMap
does not guarantee any specific iteration order of entries in the
Map
.
•
// Create a map using HashMap as the implementation class
Map<String, String> map = new HashMap<>();
// Put an entry to the map - "John" as the key and "(342)113-9878" as the value
map.put("John", "(342)113-9878");
The
LinkedHashMap
is another implementation class for the
Map
interface. It stores entries in the
Map
using a
doubly linked list. It defines the iteration ordering as the insertion order of the entries. If you want to iterate over
entries in a
Map
in its insertion order, you need to use
LinkedHashMap
instead of
HashMap
as the implementation class.
Listing 12-29 demonstrates how to use a
Map
. Note that the methods
remove()
and
get()
return the value of a
key. If the key does not exist in the
Map
, they return a
null
. You must use the
containsKey()
method to check if a key
exists in a
Map
or use the
getOrDefault()
method that lets you specify the default value in case the key does not exist
in the map. The
toString()
method returns a well-formatted string for all entries in the
Map
. It places all entries inside
braces (
{}
). Each entry is formatted in
key=value
format. A comma separates two entries. The
toString()
method of
the
Map
returns a string like
{key1=value1, key2=value2, key3=value3 ...}
.
Listing 12-29.
Using a Map
// MapTest.java
package com.jdojo.collections;
import java.util.HashMap;
import java.util.Map;
public class MapTest {
public static void main(String[] args) {
// Create a map and add some key-value pairs
Map<String,String> map = new HashMap<>();
map.put("John", "(342)113-9878");
map.put("Richard", "(245)890-9045");
map.put("Donna", "(205)678-9823");
map.put("Ken", "(205)678-9823");
// Print the details
printDetails(map);
// Remove all entries from the map
map.clear();
System.out.printf("%nRemoved all entries from the map.%n%n");