Thursday 13 February 2014

Playing with Map

My first time confusion about Map :

  1. Map is a interface not a class, so we can't create a Object of Map.
  2. Map are quite different from List , they contains key - value pair.
   import java.util.Collection;
   import java.util.HashMap;
   import java.util.Map;
   import java.util.Set;


      public class TestClass implements Map<String,String>{
          public static void main(String ...strings){
              Map<String,String> map = new HashMap<String,String>();
              map.put("1" , "first");
              map.put("2", "second");
              map.put("2", null); Map can't have duplicate elements last value override previous value.
              map.put(null, null); Key and Value both can be null.
         System.out.println(map);
         System.out.println(map.size());
     
    }
}

Output : 

{null=null, 2=null, 1=first}
3

Playing with List

Confusion which I have first time and require attention :
  1. Sometimes we confused about List that it is a class and try to create a Object of it.(First time I did this :) ). After that I realize that List is a interface.
  2. Use generic types whenever using any collection like List. Why ? According to Java doc : Generics add stability to your code by making more of your bugs detectable at compile time. (I was not aware of this first time.)

   import java.util.ArrayList;
   import java.util.Collection;
   import java.util.Iterator;
   import java.util.List;
   import java.util.ListIterator;


   public class TestClass implements List<String>{
       public static void main(String ...strings){
           List<String> list = new ArrayList<String>();
       list.add(null);      null is allowed in List.
       list.add("Ram");
       list.add("Ram"); duplicate elements are allowed in List.
       list.add(1,"Shyam"); inserts "Shyam" at position 1 and also it change index of all elements after that index.
          list.get(0);
     System.out.println(list);
     System.out.println(list.size());
   
    }
}