Saturday, 21 March 2015

Q. How Map allows primitive or integer as key ?



Ans:Map allows object as key and value.In the case of primitive like int, autoboxing (introduced in java 1.5) is done by the compiller.So primitive int is converted to Integer object by the compiller automatically.Thus, Map allows primitive int as key.


                      e.g      package com.manish;

                                 import java.util.*;

                                public class Test

                                {

                                   public static void main(String[] args)

                                    {

                                           Map mp=new HashMap();

                                           mp.put(1, 2);      // OK from 1.5

                                     }

                                 }


The same code will give compillation error when compilled in java 1.4 or lower.


                      e.g      package com.manish;

                                 import java.util.*;

                                public class Test

                                {

                                   public static void main(String[] args)

                                   {

                                     Map mp=new HashMap();

                                     mp.put(1, 2);    // Not OK compillation error in 1.4 version

                                   }

                                 }

No comments:

Post a Comment