Maps in java are very useful for storing key value pairs. Map is an interface and is a part of Collections framework.
However there are many implementations of Map interface, here I am discussing only java.util.HashMap and java.util.TreeMap.
java.util.HashMap uses its own hashing algorithm to save the keys (You don't have to worry about it !) . The advantages of hashmap is almost equal time consumption in retrieving the keys. Suppose we a million objects as keys in a HashMap then, it takes almost equal time in getting any key (hasmap.get(any key)). This performance comes at a price . You do not get keys in order . The order is completely decided by java. Lets take an example.
Let us make Person class whose objects we will store as keys in map.
So here is our Person class
{[name=X ,age=20]=2, [name=A ,age=40]=4, [name=Z ,age=10]=1, [name=D ,age=30]=3} This shows that keys are neither sorted NOR in insertion order
class Person { private int age = 0; private String name = ""; public Person(String name,int age) { this.name = name; this.age = age; } public static Person[] getPersons(){ return new Person[] {new Person("Z", 10), new Person("X", 20), new Person("D", 30),new Person("A", 40),new Person("Z", 10)}; } @Override public String toString() { return "[name="+name+" ,age="+age+"]"; } }and we now write a class to test it
public class MapTest { public static void main(String[] args) { Map<Person, Integer> hashMap = new HashMap<Person, Integer>(); show(hashMap); } public static void show(Map<Person, Integer> map){ Integer i =0; for(Person person : Person.getPersons()){ //let us put the person object as key and an integer to //indicate the position at which it is //inserted. map.put(person, ++i); } System.out.println(person); } }Probable output
{[name=X ,age=20]=2, [name=A ,age=40]=4, [name=Z ,age=10]=1, [name=D ,age=30]=3} This shows that keys are neither sorted NOR in insertion order
Comments
Post a Comment