Sunday, February 23, 2014

Collections interview questions in java

GENERAL COLLECTION QUESTIONS
LIST INTERFACE
SET INTERFACE
MAP INTERFACE
What is Java collection framework ?
A collections framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details. A collection is an object that represents a group of objects .

Why Collection does not extend Serializable or Cloneable ?
Think of a scenario where a collection is backed by a large database. Is it really meaningful to clone this collection ? I think no.
I agree that some collections might require cloning , but not all . Thats why the Collection interface does not extend Cloneable but some concrete implementations do provide a public clone method.
This holds true for Serialization as well. Serializing a collection that holds very large data is not at all good.


Why Map interface does not extends Collection interface ?
Map is not a collection of objects like List or Set , rather it is a collection of mappings ( key-value pair ) . Map and collection have a separate hierarchy because they are not compatible . Collection provides a method add() which can't be used by a map.
On the other hand , map provides collection views through the methods keySet , entrySet and values.


What is UnsupportedOperationException?
UnsupportedOperationException is a runtime exception that is used by the collections to indicate that the requested operation is not supported.


For example - UnmodifiableCollection throws this exception for add and remove methods.

What is read-only collection ? How can we create the same?
The read-only collections are those whose contents cannot be modified and any such attempt will result in UnsuppotedOperationException.
Collections utility class provides various methods that returns unmodifiable views of the specified collection.

For example , If we create a unmodifiable list and then try to add some data in it , we get UnsuppotedOperationException.


Collection readOnlyList = Collections.unmodifiableCollection(list);
// Any attempt to modify the list will result in UnsuppotedOperationException.
readOnlyList.add("new data");


What are thread safe collections ? Thread safe collection classes are those which are properly synchronized to be used in a multithreaded environment. For example Vector and Hashtable. Collections class contains some utility methods to make a thread safe collection.
For Example - Collections.synchronizedCollection returns a thread-safe collection backed by the specified collection.

What are concurrent collection classes?
Java 5 added a new Java package to the Java platform , the java.util.concurrent package.  This package contains a set of classes that makes it easier to develop concurrent applications in Java.
Some examples are :
ConcurrentMap
ConcurrentNavigableMap
CountDownLatch


What is List interface? What are its main implementations?
List is an ordered collection of elements ( also known as sequence ) . The ordering is index based. A list can have duplicate elements in it and permite multiple null values.
ArrayList , LinkedList , Stack , Vector are some of its implementations.


What is the difference between Array and ArrayList?

  • ArrayList is a growing array . That means the size of an Array is fixed but the ArrayList can grow dynamically.The size of an array need to be defined at the time of its initialization.
  • Array can contain primitives or Objects whereas ArrayList can only contain Objects.
  • ArrayList provides a lot more methods for insertion/retrieval of data as compared to an array.


What is the difference between ArrayList and Vector?

  • Vector is synchronized whereas ArrayList is not.
  • ArrayList is faster than Vector because it is not synchronized. 
  • By default , Vector doubles the size of its array when it is re-sized internally , whereas an ArrayList increases by half of its size when re-sized. 

In general ArrayList is prefered over Vector because we can easily get an unmodifiable list or a synchronized list by using methods of Collections class.


What is the difference between ArrayList and LinkedList?

  • LinkedList stores the elements in a doubly-linked list where as ArrayList is backed by an array.
  • Adding and removal of elements is faster in a LinkedList (constant time insertion or removal ) .The addition and removal of elements is slower in an array because it involves shifting of elements when an element is added in the middle.
  • Searching an element is faster in ArrayList as it allows random access and thus gives constant time performance. 


How to get an array from an ArrayList?
List contains  method toArray that can be used for converting a list into an array.
Example :
List<String> names = new ArrayList<String>();
list.add("prakash");
list.add("chauhan");
list.add("java");
list.add("world");


String [] namesArray = names.toArray(new String[list.size()]);


How to sort list in reverse order?
Use reverse method of Collections utility class.
Collections.reverse(list);

How to convert an array of String to ArrayList?
The utility class Arrays provides a method asList that can be used to convert a list into an array.
Example :
String[] namesArray = {"prakash", "chauhan", "java", "world"};
List names = Arrays.asList(words);



What is Set interface ?
Set is the collection of unique elements i.e it does not support duplicate elements. Set is an unordered collection.
Some of the concrete implementations are HashSet , LinkedHashSet , TreeSet


What is EnumSet?
EnumSet is Set implementation to use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. EnumSet is not synchronized and null elements are not allowed. Any attempt to insert null element will throw NullPointerException.


Difference between HashSet and TreeSet ?
HashSet is Implemented using a hashtable. HashSet is unordered collection . The add, remove, and contains methods have constant time complexity O(1).
TreeSet is implemented using a red-black tree. TreeSet is a sorted collection , but add, remove, and contains methods has time complexity of O(log (n)). It offers several methods to deal with the ordered set like first(), last(), headSet(), tailSet(), etc.


What is Map?
Map is collection of mappings i.e key-value pairs. It does not extend Collection interface.
Map is an object that maps keys to values. A map cannot contain duplicate keys and each key can map to at most one value.

Some concrete implementations of map are HashMap, Hashtable, LinkedHashMap.

What are different collection views provided by Map interface?
Three collection views are provided by Map :
  • keySet() : Returns a Set view of the keys contained in the map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
  • values(): Returns a Collection view of the values contained in the map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
  • entrySet(): Returns a Set view of the mappings contained in the map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.


What is the difference between HashMap and Hashtable?
HashMap and Hashtable both implements Map interface. Below are some differences between them : 
  • Hashtable is synchronized but HashMap is not . Choose Hashtable if thread safety is a concern.
  • HashMap allows one null key and multiple null values whereas Hashtable doesn’t allow anything that is null.
what is capacity and load factor in HashMap?
The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. 
When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

What is collision in HashMap?
Collision occurs in a HashMap if two objects have same hashcode . Now because the hascode is same , bucket location needs to be the same for both the objects .
In such a situation , HashMap uses a linked list to store objects.


What is the difference between HashMap and TreeMap?

  • HashMap is an unordered collection whereas TreeMap is sorted.
  • For inserting, deleting, and locating elements in a Map, the HashMap is the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is the right choice .

Depending upon the size of collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorting.

8 comments :

  1. Very helpful post for interview seekers.

    Good job.

    ReplyDelete
  2. Good questions, but your links are broken, they are seems to going no where. By the way, I have also shared some 25 questions from Java collections for Interviews, let me know if you find it useful. Thanks

    ReplyDelete
    Replies
    1. Yes I have just realized that the links r not working properly . Thanks for pointing it out.

      Yes the link u shared is useful ( infact all your posts are great :) ).

      Delete
  3. Hello! I just finished reading your blog and I think it's really helpful. I had already been looking for some tips on Java interview questions and some general tips on star interview questions and answers. I think these things are really important when you are going for an interview in a government organisation and in even in big private ones. Thanks a lot.

    ReplyDelete
  4. Hey! I just finished reading your blog and I think it's really helpful. I've been searching the Internet for some general tips on star interview questions and answers and Java interview questions but I wasn't able to find satisfactory results. Thanks God I came across your blog and it has proved to be worth while.

    ReplyDelete

  5. A list of few more java interview questions like

    1. By default, Java is pass by reference or pass by value. how it handles it.
    2. In which scenario, you will use custom exceptions in java.
    3. how garbage collection works in java
    4. what is autoboxing and unboxing in java
    5. how hashmap works in java

    For more questions:
    Check more information on java interview questions and tutorials

    ReplyDelete