Java HashMaps are a powerful Key/value pair container. Using a unique key they provide fast access the the value associated with that key. In this tutorial I'll cover a basic usage example, how to iterate, check if a key value exists and how to create your own objects to act as a key (or value). The basics covered here are intended to provide a starting point for using Java collections.
HashMaps contain a list of key/value pairs. The type of objects stored as the key and value are declared when the collection is created. This is an example of Java generics and provides compile time checking to ensure you only add the allowed type of objects to the HashMap.
Map<String,String> example = new HashMap<String,String>();
// Adding some values to the HashMap
example.put( "Wayne", new String( "Rooney" ));
example.put( "Alan", new String( "Shearer" ));
example.put( "Rio", new String( "Ferdinand" ));
example.put( "John", new String( "Terry" ));
// Find out how many key/value pairs the HashMap contains
System.out.println("The HashMap contains " + example.size() + " pairs"Line 2. creates a new HashMap object and sets the key and value object types to String objects. Notice that the HashMap implements the Map<K,V> interface.
Line 5. shows the use of the .put() method to add the key and value objects as a new pair.
Line 11. prints the size of the HashMap to the console. In this case it will show that it contains 4 key/value pairs.
Checking for a key
Checking if a HashMap contains a specific key is a fast operation when compared to a linear search through a list such as a Vector.
String newKey = "Ian";
if ( !example.containsKey( newKey ) ) {
example.put( newKey, new String( "Wright" ) );
}
This example checks if the HashMap contains a specific key. If the key is not contained in the Map a new key/value pair are added.
HashMap iterators
There are a number of ways to iterate through the pairs in a HashMap.
for (String key : example.keySet() ) {
// Get the String value that goes with the key
String value = example.get( key );
// Print the key and value
System.out.println( key + " = " + value);
}
//The method shown above is available in Java 1.5 onwards. It is a much easier to read (and code) way of iterating through a set of objects. If it were to be run it would produce the following output.
Wayne = Rooney
Alan = Shearer
Rio = Ferdinand
John = Terry
Ian = Wright
Custom key objects
//Any object can be used for the key or value in a Map. Two methods must be implemented for this to work properly however: the hashCode() and equals() methods. An example of this might be the following.
public class SoccerPlayer {
private String firstname;
private String surname;
public SoccerPlayer(String firstname, String surname)
this.firstname = firstname;
this.surname = surname;
}
public String toString() {
return surname + ", " + firstname;
}
public int hashCode() {
return this.toString().hashCode();
}
public boolean equals(Object player) {
// Check the object is valid and is of the correct class type
if ( player == null ) return false;
if ( this.getClass() != player.getClass() ) return false;
// It is now safe to cast to SoccerPlayer and compare the classes data members
String name = ((SoccerPlayer)player).toString();
return this.toString().equals(name);
}
}
Remember that keys in a HashMap must be unique, so using enough information from within your object to create a unique hashcode is important. In this case, if another object contained the same firstname and surname, it would over-write the first key value, but that would be ok since I can be sure they are the same. If the example contained amiddlename variable, but the hashcode did not take this into account there might be a situation where the hashcodes for two different keys are the same.
The equals() method overrides the default implementation in Object. The equals() method in Object only compares the objects references, known as a shallow comparison, since Object does not contain any data members of its own. The implementation of equals() you provide, as like the one above must compare the data members of the class to ensure equality. This is called a deep comparison.
Thanks for your informative post about hashmaps. Salesforce Training in Chennai
ReplyDelete