Thursday, 5 June 2014

Collection Interview Questions and Answers in Java(List,Map & Set)

          The Collection is the most important topic in Java.  The Collection Interview questions mostly on ArrayList, HashMap, LinkedList, LinkedHashMap, LinkedHashSet and so on.
           I have shared some interview questions and answers as below.

1)  What is the difference between Collection and Collections ?
          
       Collection is an interface while Collections is a Java class, both are present in java.util package and a part of java collections framework.

2) Why Map Interface doesn't extend Collection interface?

      Refer this link, Why Map interface doesn't extend Collection interface?


3)  What is the difference between Collection and Collections ?

Collection : - Collection is the interface in the Collection framework in java. All interfaces like List, Set and Queue interfaces can extend the root collection interface.

Collections:- It is the utility class in Collection and provides several methods like sort, reverse, synchronizedList, synchronizedSet, synchronizedMap and binarySearch etc.


4) What are the classes implementing List and Set interface?

      ArrayList, Vector and LinkedList classes are implementing List interaface. HashSet and TreeSet classes are implementing Set interface.


5) Which collection classes are thread safe ?

          Vector, Hashtable, Properties and Stack are synchronized classes, so they are thread safe and can be used in multi-threaded environment.


6) How HashMap works internally in Java ?

           This is one of the most important question for Java Developers. HashMap works on the principle of Hashing. For Detailed information How HashMap works internally in java.


7) How to convert the array of Strings into the list ?

           Arrays class of java.util package contains the method asList() which accepts the array as parameter.

                        String arr[] = {"Insta", "Practo"};
                        List listOfString = Arrays.asList(arr);



8) How to make a collection read only ?
        
       Use following methods to make a collection read only,

                       Collections.unmodifiableList(list);
                       Collections.unmodifiableSet(set);
                       Collections.unmodifiableMap(map);


9) How to make a collection thread safe ?
      
      Use following methods to make a collection thread safe,

                       Collections.synchronizedList(list);
                       Collections.synchronizedMap(map);
                       Collections.synchronizedSet(set);


10) Difference between HashMap and Hashtable in java.
     
     Refer this Difference between HashMap and Hashtable in collection in Java


11) Difference between ConcurrenHashMap and Hashtable.

       Both ConcurrentHashMap and Hashtable are synchronization in nature. For consideration of performance, ConcurrentHashMap is good because it is locked the particular segment but in Hashtable it will lock the whole object.


12) Difference between the HashMap, LinkedHashMap and TreeMap.

       All these three classes can implement the java.util.Map interface. Differences are as follows,

        HashMap can not maintain any order for inserting key or for getting key from map. But in LinkedHashMap , it can maintain the same insertion order. TreeMap can give the Natural order.

        HashMap can allow one null key and multiple null values, LinkedHashMap also can allow one null key and multiple null values. But TreeMap doesn't allow the null keys.
     

13)  How ArrayList works internally in Java?

     I have written separate post for internal working concept of ArrayList in Collection, Refer  Internal Implementation of ArrayList

14) How LinkedList works internally in Java ? 

     I have written separate post for internal working concept of LinkedList in Collection, Refer  Internal Implementation of LinkedList


15) What are the different ways to iterate over the list ?

        There are two ways to iterate over a list - using for-each loop and another one using iterator interface.
   
             ArrayList<String> arrList = new ArrayList<String>();
          
              //using for-each loop
             for  (String name : arrList )  {
                    System.out.println(name);
             }
   
              //using iterator interface
             Iterator<String>  iterator = arrList.iterator();
             while (iterator.hasNext()) {
                     System.out.println(iterator.next());
             }


16) What is fail-fast & fail-safe property in Iterator?

          In fail-fast property, every time while iterating the list it will check for the modification in the list, If any modification found then it will throw ConcurrentModificationException errors. All the implementations of iterator in Collection classes are fail-fast except concurrent classes like ConcurrentHashMap and CopyOnWriteArrayList.
          
          In fail-safe property, while iterating the list it won't throw any exception i.e ConcurrentModificationException even if you modified the list. All implementations of Collection classes in java.util package are fail-fast and all Collections classes of java.util.concurrent are fail-safe.
Examples of fail-safe classes are ConcurrentHashMap and CopyOnWriteArrayList.



17)  HashMap Related Question--

                        HashMap<String,String> map=new HashMap<String,String>();
                        map.put("one", new Integer(1));
                        map.put("one", new Float(1.0));
                        System.out.println(map.get("one"));

                In which value it will print? 1 or 1.0?

  It will print 1.0 because if map having the same keys then it can override
                the previous key value. 


18) See below code--

                        HashMap<String,Integer> map=new HashMap<String,Integer>();
                        String s="anil";
                        map.put(s,1);
                        s=s+"nivargi";
                        System.out.println(map.get(s));

                     what would be the output?will give error or what?

     Output is -  null.


19)  How to loop or iterate the Map or HashMap in java?Explain
  
     There are two ways (i know) to iterate the Map or HashMap
                     1)Using iterator interface
                     2)using Enhanced for loop
      See below code------
       Here you can use Map.Entry interface .
                           package com.adnblog;
                           import java.util.HashMap;
                           import java.util.Iterator;
                           import java.util.Map;
                           public class ItertionMap{
                                      public static void main(String[] args){
                                                   Map<String,String> map=
                                                                             new HashMap<String,String>();
                                                    map.put("1","one");
                                                    map.put("2","two");
                                                    map.put("3","three");
                                                          //first type i.e using iterator interface
                                                    Iterator iterator=map.entrySet().iterator();
                                                    while(iteartor.hasNext()){
                                                              Map.Entry mapEntry=
                                                                                (Map.Entry)iterator.next();
                                                              System.o.p("key--"+mapEntry.getKey()+
                                                                                "value "+mapEntry.getValue());
                                                    }                     
                                                            //second type using forEach loop
                                                    for(Map.Entry<String,String> entry: map.entrySet()){
                                                                System.out.println("key--"+entry.getKey()+
                                                                                  "value "+entry.getValue());
                                                    } 
                                    }
                          }

20) What is UnsupportedOperationException in Collection ? and when it will throw?

            The Exception itself indicates that given operation is not supported. This will throw when we are modifying the unmodifiable collection.
            e.g
                   List<String> list = new ArrayList<String>();
                   list.add("Insta");
                   List<String> unmodifiableList = Collections.unmodifiableList(list);
                   unmodifiableList.add("Practo");       //will throw the exception. 
                

 21) What is ConcurrentModificationException in collection? in which situation it will  come? give me example.   
             
           The java.util Collection classes are fail-fast, which means that if one thread changes a collection while another thread is traversing it through with an iterator the iterator.hasNext() or iterator.next() call will throw  ConcurrentModificationException This situation can come in case of  multithreaded as well as single threaded environment. 
          Lets see the scenario with an example:

                             import java.util.*;
                             public class IteratorEx{
                                     public static void main(String[] args){
                                              List<String> list=new ArrayList<String>();
                                              list.add("one");
                                              list.add("two");
                                              list.add("three");
                                              Iterator<String>  it=list.iterator();
                                              while(it.hasNext()){
                                                      String key=it.next();
                                                       if(key.equals("two")){
                                                              list.remove("two");    //will throw error
                                                       }
                                             }
                                     }
                            }

                 How to handle the
ConcurrentModificationException:--

1)  The list can be converted to an array with list.toArray() and iterate on the array.  This approach  is not recommended if the list is large. 

2)  You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of  multithreading .

3) If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.

4)  if you are removing element from collection then use iterator remove method instead of collection remove method .


22) ConcurrentHashMap retrieval operation does not take lock?

             Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries



Related Post:-- 
Internal implementation of ArrayList in Java  
Internal Implementation of LinkedList in Java 
String Interview Questions and Answers
Exception Handling Interview questions and answers
Difference between Loose Coupling and Tight Coupling in Java With Examples.

No comments:

Post a Comment