Explain about Map and their types.
Map cares about unique identifier. We can map a unique key to a specific value. It is a key/value pair. We can search a value, based on the key. Like set, Map also uses “equals ( )” method to determine whether two keys are same or different.
Hash Map:
- Unordered and unsorted map.
- Hashmap is a good choice when we don’t care about the order.
- It allows one null key and multiple null values.
Example:
Public class Fruit{
Public static void main(String[ ] args){
HashMap<Sting,String> names =new HashMap<String,String>( );
names.put(“key1”,“cherry”);
names.put (“key2”,“banana”);
names.put (“key3”,“apple”);
names.put (“key4”,“kiwi”);
names.put (“key1”,“cherry”);
System.out.println(names);
}
}
Output:
{key2 =banana, key1=cherry, key4 =kiwi, key3= apple}
Duplicate keys are not allowed in Map.
Doesn’t maintain any insertion order and is unsorted.
Hash Table:
- Like vector key, methods of the class are synchronized.
- Thread safety and therefore slows the performance.
- Doesn’t allow anything that is null.