Sunday, 11 May 2014

Java Collection Interview Questions

Java Interview Questions.
  1. What is Java Collections framework?
  2. What are the advantages of Collection framework?
  3. What are the interfaces in Java Collection?
  4. What are the implementation classes in Java Collection framework?
  5. What is an Iterator?
  6. What are the difference ways to iterate a List?
  7. What are different Collection classes and how are they different from each other?
  8. How does different Java Collections work internally?
  9. What is difference between HashMap and Hashtable?
  10. How to decide between HashMap and TreeMap?
  11. What is difference between Array and ArrayList? When will you use Array over ArrayList?
  12. What is difference between ArrayList and LinkedList?
  13. How can we sort a list of Objects?
  14. Write a code to sort and remove duplicates in an array using Collection framework?
  15. Provide Custom Implementation of Collection classes?
  16. What are the different features provided by Java 8 Lambda and Collection Streams?
  1. What is Java Collections framework?


    The Java collection is a framework which consists of set of interfaces and classes which provide built in data structures like List, Map, Set, Queue etc. The Collections framework enables the programmer to store, manipulate and retrieve the data present in the collection. 
  2. What are the advantages of Collection framework?

    The Java Collections Framework provides the following benefits:
    Reduces programming effort: By providing useful data structures and algorithms, the Collections Framework frees you to concentrate on the important parts of your program rather than on the low-level "plumbing" required to make it work. By facilitating interoperability among unrelated APIs, the Java Collections Framework frees you from writing adapter objects or conversion code to connect APIs.
    Increases program speed and quality: This Collections Framework provides high-performance, high-quality implementations of useful data structures and algorithms. The various implementations of each interface are interchangeable, so programs can be easily tuned by switching collection implementations. Because you're freed from the drudgery of writing your own data structures, you'll have more time to devote to improving programs' quality and performance.
    Allows interoperability among unrelated APIs: The collection interfaces are the vernacular by which APIs pass collections back and forth. If my network administration API furnishes a collection of node names and if your GUI toolkit expects a collection of column headings, our APIs will interoperate seamlessly, even though they were written independently.
    Reduces effort to learn and to use new APIs: Many APIs naturally take collections on input and furnish them as output. In the past, each such API had a small sub-API devoted to manipulating its collections. There was little consistency among these ad hoc collections sub-APIs, so you had to learn each one from scratch, and it was easy to make mistakes when using them. With the advent of standard collection interfaces, the problem went away.
    Reduces effort to design new APIs: This is the flip side of the previous advantage. Designers and implementers don't have to reinvent the wheel each time they create an API that relies on collections; instead, they can use standard collection interfaces.
    Fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable. The same goes for new algorithms that operate on objects that implement these interfaces.
  3. What are the interfaces in Java Collection?

    The image below describes the hierarchy of the interfaces in the Collection Framework:

    As seen above the Collection interface sits at the top of the hierarchy. It has few methods that are common to all the Collection classes like add(), remove(), size(), iterator() etc. One more thing to notice here is the Map interface, it does not extend the Collection interface.
  4. What are the implementation classes in Java Collection framework?


    Below two image shows the complete hierarchy of interfaces and classes present in the Collection framework.


    The Collections come in basic four flavours: Lists : List of things ( Classes that implement List Interface) Sets : Unique things ( Classes that implement Set Interface)Maps : Things with unique id ( Classes that implement Map Interface) Queues : Things arranged in order ( Classes that implement QueueInterface)
              Below table shows the different concrete classes implementing these interfaces
    Maps
    Sets
    Lists
    Queues
    Utilities
    HashMap
    HashSet
    ArrayList
    PriorityQueue
    Collections
    Hashtable
    LinkedHashSet
    Vector
    Arrays
    TreeMap
    TreeSet
    LinkedList
    LinkedHashMap


  5. Iterator is a class which is used to iterate over a collection. Generally after the for each loop was introduced the use of iterator is not advised. Below code snippet shows the use of Iterator
  6. There are two ways to iterate over a collection or List. Either by using the Iterator class as mentioned above or using the for each loop. Using for each is much cleaner.
  7. How does different Java Collections work internally?


    This is becoming a very important question in interviews. Interviewers now a days do not just asks the basics of collection instead they ask the internal working of the collection classes. They might also ask the developer to write down the code to implement one if the collection classes.

    To understand how different Java Collections work internally refer this post : Java Collections : Internal Working
  8. HashMap provides fast searching but the values are not sorted if we try to iterate a HashMap instead of finding a value. In cases where finding by key and iterating with sorted order is needed in that case a TreeMap can be used.
  9. ArrayList is created using a Array Internally. While using an Array the size needs to be defined. But there is no need to define size in case of ArrayList. ArrayList increases its size as elements gets added by creating a new array. This makes ArrayList slower than Array. 

    So a Array can be used when the size is known and fix and fast access is required. Use ArrayList when the size is not defined.
  10. ArrayList uses Array Internally. So it copies all elements and creates a bigger array internally when elements are added. LinkedList on the other hand uses a Doubly Linked List, which can grow without copying anything. 

    ArrayList internally uses array so adding elements in between a ArrayList requires lot of computation as a new array is created. On the other hand LinkedList since it is Doubly Linked List nodes/elements can be added at any position. So LinkedList is better is elements are not to be added by position.

    Retrieving a element by its position is faster in ArrayList as it uses Array Internally. When retriving a element by its position in LinkedList, the LinkList needs to traverse to that node.
  11. There are multiple ways to sort a collection. Sorting is not required for collection who do use Tree like TreeSet or TreeMap. For the rest of the collections java provides static method sort in Collections class. Make sure that elements of Collection passed to the sort method are implementing comparator interface. 
    Many a times interviewers ask such questions. This is just one of them. Below is the code to sort and remove duplicates from an array

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    import java.util.Set;
    import java.util.TreeSet;
    
    
    public class Test {
    
     public static void main(String[] args) {
      
      // an array that has duplicate and un-orderd numbers
      // Use Java collections to remove duplicates and order the array
    
      Integer arr[]={1,-1,2,4,-5,1,3,2};
      
      List list = new ArrayList();
      //Convert array to list
      list=Arrays.asList(arr);
      
      //Sort the list
      Collections.sort(list);
      
      //Add the list to Treeset
      Set s= new TreeSet(list);
      
      Integer newarr[] = new Integer[s.size()];
      
      // Add elements of Treeset into array
      s.toArray(newarr);
      
      // Here you go. Sorted elements in the array
      for(Integer a1 : newarr){
       System.out.println(a1);
      }
     }
    
    }
    
    Output below:
    -5
    -1
    1
    2
    3
    4
Custom implementation of Collections and Data Structure:
ArrayList
LinkedList
HashMap











  • Refer Java 8 Lambda Expression for the complete understanding of Java 8 Streams. Streams allow you to filter, sort, map a collection easily.


    Java Interview Questions for 2 to 5 years

    Share the post