Java Interview Questions - Collections

Here is a set of Java Interview Questions which focuses on the Collections framework. You can find the previous set of Interview Questions from here:

1. What is Collection API?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
2. What are the classes implementing List interface?
There are three classes that implement List interface:
  1. ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.
  2. Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.
  3. LinkedList: LinkedList implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster than ArrayList for insertion and deletion of elements from the middle of a list.
3. Which all classes implement Set interface?
A Set is a collection that contains no duplicate elements. HashSet, SortedSet and TreeSet are the commonly used classes which implements Set interface.
  1. SortedSet - It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
  2. TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.
  3. HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.
4. What is difference between List and a Set?
  • List can contain duplicate values but Set allows only unique elements.
  • List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.
5. What is difference between Arrays and ArrayList ?
  1. Arrays are created of fix size whereas ArrayList is of not fix size. i.e. the size of array cannot be incremented or decremented. But with arrayList the size is variable.
  2. Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.
  3. ArrayList is one dimensional but array can be multidimensional.
  4. To create an array the size should be known or initalized to some value. If not initialized carefully there could me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory.
6. What are the main differences between a Vector and an ArrayList?
  1. Synchronization - Java Vector class is internally synchronized and ArrayList is not synchronized. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure (ArrayList) will give better performance than the synchronized one (Vector).
  2. Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
7. Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
The LinkedList allows for fastest insertions and deletions into the middle of a list. The LinkedList is implemented using a doubly linked list; thus an insertion requires only the updating of the links at the point of insertion.Whereas ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list, then the elements that follow the insertion point must be shifted to make room for the new element.
8. What is difference between HashMap and HashTable?
Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
  1. Hashmap is not synchronized in nature but HashTable is.
  2. Iterator in the HashMap is fail-safe while the enumerator for the HashTable isn't.
  3. HashMap permits null values and only one null key, while HashTable doesn't allow key or value as null.
    9. Is Iterator a Class or Interface? What is its use?
    Iterator is an interface which is used to step through the elements of a Collection.
    10. If any ArrayList is used only for reading which way will be the faster, For loop or Iterator?
    Using a for loop is faster than using iterator. A for loop allows access of the element directly on the basis of index. The cursor of the datastructure can directly go to the 'n' location and get the element. It does not traverse through n-1 elements. Wheras in Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the 'n'th element it need to traverse through n-1 elements.
    11. When should be an Iterator preferred over a For loop?
    For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where the data type of the collection is not known.
    12. How do you traverse through a collection using its Iterator?
    To use an iterator to traverse through the contents of a collection, follow these steps:
    1. Obtain an iterator to the start of the collection by calling the collection’s iterator() method.
    2. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
    3. Within the loop, obtain each element by calling next().
    13. How can Arraylist be synchronized without using Vector?
    Arraylist can be synchronized using:
    Collection.synchronizedList(List list) 
    14. What is identityHashMap?
    The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.
    15. What are the main algorithms (methods) that the Collections framework provide?
    Most polymorphic algorithms in the Collections class apply specifically to List. Below listed are the commonly used algorithms :
    • sort — sorts a List using a merge sort algorithm, which provides a fast, stable sort. (A stable sort is one that does not reorder equal elements.)
    • shuffle — randomly permutes the elements in a List.
    • reverse — reverses the order of the elements in a List.
    • rotate — rotates all the elements in a List by a specified distance.
    • swap — swaps the elements at specified positions in a List.
    • replaceAll — replaces all occurrences of one specified value with another.
    • binarySearch — searches for an element in an ordered List using the binary search algorithm.


    Post a Comment

    Related Posts Plugin for WordPress, Blogger...

    Copyright © 2012 | ScriptSplash | Powered by Blogger Templates