This example shows how to create hash map and perform some operations on it.
public static Map createMap(){
// Create a hash table
Map map = new HashMap(); // hash table
//Map map = new TreeMap(); // you can do sorted
//map as well
// Add key/value pairs to the map
map.put("a", 1);
map.put("b", new Integer(2));
map.put("c", new Integer(3));
// Get number of entries in map
int size = map.size(); // 2
// Adding an entry whose key exists in the map causes
// the new value to replace the old value
Object oldValue = map.put("a", new Integer(9)); // 1
// Remove an entry from the map and return the value of the removed entry
oldValue = map.remove("c"); // 3
boolean isempty = map.isEmpty();
return map;
}
As putting a duplicate key value, pair changes value, use containsKey() and containsValue(), a programmer can check the existence of a key or value with the HashMap.
No comments:
Post a Comment