Collections Interview Questions:-


  What is Java Collections Framework? List out some benefits of Collections framework?

Collections are used in every programming language and initial java release contained few classes for collections: Vector, Stack, Hashtable, Array. But looking at the larger scope and usage, Java 1.2 came up with Collections Framework that group all the collections interfaces, implementations and algorithms.

Java Collections have come through a long way with usage of Generics and Concurrent Collection classes for thread-safe operations. It also includes blocking interfaces and their implementations in java concurrent package.


  What is the benefit of Generics in Collections Framework?

Java 1.5 came with Generics and all collection interfaces and implementations use it heavily. Generics allow us to provide the type of Object that a collection can contain, so if you try to add any element of other type it throws compile time error.

This avoids ClassCastException at Runtime because you will get the error at compilation. Also Generics make code clean since we don't need to use casting and instanceof operator. I would highly recommend to go through Java Generic Tutorial to understand generics in a better way.


  What is the root interface in collection hierarchy ?

Root interface in collection hierarchy is Collection interface.Collection interface extends Iterable interface.So iterable should be the root interface. But you should reply iterable interface present in java.lang package not in java.util package .It is clearly mentioned in Oracle Collection docs , that Collection interface is a member of the Java Collections framework. For Iterable interface Oracle doc , iterable interface is not mentioned as a part of the Java Collections framework .So if the question includes collection hierarchy , then you should answer the question as Collection interface (which is found in java.util package).


  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 part of java collections framework.


  What is the difference between List and Set ?

Set contain only unique elements while List can contain duplicate elements. Set is unordered while List is ordered . List maintains the order in which the objects are added .


  What is the difference between Map and Set ?

Map object has unique keys each containing some value, while Set contain only unique values.


  What are the classes implementing List and Set interface ?

Class implementing List interface : ArrayList , Vector , LinkedList , Class implementing Set interface : HashSet , TreeSet


  What is an iterator ?

Iterator is an interface . It is found in java.util package. It provides methods to iterate over any Collection.Basically List and set collection provides the iterator.You can get Iterator from ArrayList, LinkedList, and TreeSet etc.

Map implementation such as HashMap doesn't provide Iterator directory but you can get there keySet or Value Set and can iterator through that collection.


  What is Difference between fail-safe and fail-fast Iterator in Java?

fail-fast Iterators in Java

As name suggest fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun. Structural changes means adding, removing or updating any element from collection while one thread is Iterating over that collection.

fail-fast behavior is implemented by keeping a modification count and if iteration thread realizes the change in modification count it throws ConcurrentModificationException.

fail-safe Iterator in java

Contrary to fail-fast Iterator, fail-safe iterator doesn't throw any Exception if Collection is modified structurally while one thread is Iterating over it because they work on clone of Collection instead of original collection and that's why they are called as fail-safe iterator.


  Which design pattern followed by Iterator ?

It follows iterator design pattern. Iterator design pattern provides us to navigate through the collection of objects by using a common interface without letting us know about the underlying implementation.


  What is difference between HashMap and Hashtable in Java?

Both HashMap and Hashtable implements Map interface. Here are two differences :

1.The HashMap class is roughly equivalent to Hashtable, except that it is non-synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).

2. One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap can not be shared between multiple threads without proper synchronization.


  Which methods you need to override to use any object as key in HashMap ?

To use any object as key in HashMap , it needs to implement equals() and hashCode() method .


  What is the difference between java.util.Iterator and java.util.ListIterator?

1. Iterator : Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements

2. ListIterator : extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.


  What does synchronized means in Hashtable context?

Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.


  Why doesn't Collection extend Cloneable and Serializable?

Many Collection implementations (including all of the ones provided by the JDK) will have a public clone method, but it would be mistake to require it of all Collections.

For example, what does it mean to clone a Collection that's backed by a terabyte SQL database? Should the method call cause the company to requisition a new disk farm? Similar arguments hold for serializable.

If the client doesn't know the actual type of a Collection, it's much more flexible and less error prone to have the client decide what type of Collection is desired, create an empty Collection of this type, and use the addAll method to copy the elements of the original collection into the new one.


  What is the Difference between Enumeration and Iterator interface?

Enumeration and Iterator are the interface available in java.util package. The functionality of Enumeration interface is duplicated by the Iterator interface. New implementations should consider using Iterator in preference to Enumeration. Iterators differ from enumerations in following ways:

1. Enumeration contains 2 methods namely hasMoreElements() and nextElement() whereas Iterator contains three methods namely hasNext(), next(),remove().

2. Iterator adds an optional remove operation, and has shorter method names. Using remove() we can delete the objects but Enumeration interface does not support this feature.

Enumeration interface is used by legacy classes. Vector.elements() and Hashtable.elements() method returns Enumeration. Iterator is returned by all Java Collections Framework classes. java.util.Collection.iterator() method returns an instance of Iterator.


  What is the difference between Sorting performance of Arrays.sort() vs Collections.sort() ? Which one is faster? Which one to use and when?

Many developers are concerned about the performance difference between java.util.Array.sort() java.util.Collections.sort() methods. Both methods have same algorithm the only difference is type of input to them. Collections.sort() has a input as List so it does a translation of List to array and vice versa which is an additional step while sorting.

So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array. So clearly it should be used when you have a array available with you and you want to sort it.


  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 part of java collections framework.


  Why Map interface does not extend the Collection interface in Java Collections Framework ?

Map interface is not compatible with the Collection interface. Explanation : Since Map requires key as well as value , for example , if we want to add key-value pair then we will use put(Object key , Object value) . So there are two parameters required to add element to the HashMap object . In Collection interface add(Object o) has only one parameter.

The other reasons are Map supports valueSet , keySet as well as other appropriate methods which have just different views from the Collection interface.


  What is CopyOnWriteArrayList ? How it is different from ArrayList in Java?

CopyOnWriteArrayList is a thread safe variant of ArrayList in which all mutative operations like add , set are implemented by creating a fresh copy of the underlying array.

It guaranteed not to throw ConcurrentModificationException. It permits all elements including null. It is introduced in jdk 1.5 .


  What is BlockingQueue in Java Collections Framework?

BlockingQueue implements the java.util.Queue interface . BlockingQueue supports operations that wait for the queue to become non-empty when retrieving an element , and wait for space to become available in the queue when storing an element . It does not accept null elements.

Blocking queues are primarily designed for the producer-consumer problems. BlockingQueue implementations are thread-safe and can also be used in inter-thread communications.

This concurrent Collection class was added in jdk 1.5


  What is EnumSet in Java ?

EnumSet is a specialized Set implementation for 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.

The iterator never throws ConcurrentModificationException and is weakly consistent. Advantage over HashSet:

All basic operations of EnumSet execute in constant time . It is most likely to be much faster than HashSet counterparts.

It is a part of Java Collections Framework since jdk 1.5.


  What is IdentityHashMap ?

IdentityHashMap is a class present in java.util package. It implements the Map interface with a hash table , using reference equality instead of object equality when comparing keys and values.In other words , in IdentityHashMap two keys k1 and k2 are considered equal if only if (k1==k2).

IdentityHashMap is not synchronized.

Iterators returned by the iterator() method are fail-fast , hence , will throw ConcurrentModificationException.


  What is WeakHashMap ?

WeakHashMap :

WeakHashMap is a class present in java.util package similar to IdentityHashMap. It is a Hashtable based implementation of Map interface with weak keys. An entry in WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector.

It permits null keys and null values.

Like most collection classes this class is not synchronized.A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap() method. Iterators returned by the iterator() method are fail-fast , hence , will throw ConcurrentModificationException.


  Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?

List interface has three main implementation classes :-

1. Vector

2. ArrayList

3. LinkedList

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 the elements that follow the insertion point must be shifted to make room for the new element.

The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.


  What is EnumMap in java?

A java.util.EnumMap is specialized Map implementation for use with enum type keys.

EnumMap all keys comes from a single enum type that is specified when the set is created in java.

Order of keys in EnumMap in java

The EnumMap maintains natural order (the order in which the enum constants are declared) of keys in java.

Iterator on EnumMap in java

The iterator returned by the iterator method in EnumMap traverses the elements in their natural order of keys(the order in which the enum constants are declared).

iterator never throw ConcurrentModificationException and it may or may not show the effects of any modifications to the map that occur while the iteration is in progress in java.

Null allowed in EnumMap in java?

Null keys are not allowed in EnumMap. Attempts to insert a null key will throw NullPointerException. But, Null values are allowed in EnumMap in java.


  What is Comparable and Comparator interface?

In java. all collection which have feature of automatic sorting, uses compare methods to ensure the correct sorting of elements. For example classes which use sorting are TreeSet, TreeMap etc.

To sort the data elements a class needs to implement Comparator or Comparable interface.That's why all Wrapper classes like Integer,Double and String class implements Comparable interface.

Comparable helps in preserving default natural sorting, whereas Comparator helps in sorting the elements in some special required sorting pattern. The instance of comparator if passed usually as collection's constructor argument in supporting collections.


  What are Collections and Arrays classes?

Collections and Arrays classes are special utility classes to support collection framework core classes.They provide utility functions to get read-only/ synchronized collections, sort the collection on various ways etc.

Arrays also helps array of objects to convert in collection objects. Arrays also have some functions which helps in copying or working in part of array objects.


  What is Queue and Stack, list down their differences?

A collection designed for holding elements prior to processing.Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations.

Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner.

Stack is also a form of Queue but one difference, it is LIFO (last-in-first-out).

Whatever the ordering used, the head of the queue is that element which would be removed by a call to remove() or poll(). Also note that Stack and Vector are both synchronized.

Usage:Use a queue if you want to process a stream of incoming items in the order that they are received.Good for work lists and handling requests. Use a stack if you want to push and pop from the top of the stack only. Good for recursive algorithms.


  Which collection classes provide random access of it's elements?

ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it's elements.


  What is BlockingQueue?

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

BlockingQueue methods come in four forms: one throws an exception, the second returns a special value (either null or false, depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up.


  How to make a collection read only?

Use following methods:

(a). Collections.unmodifiableList(list);

(b). Collections.unmodifiableSet(set);

(c). Collections.unmodifiableMap(map);

These methods takes collection parameter and return a new read-only collection with same elements as in original collection.


  Difference between List and Map?

List is collection of elements where as map is collection of key-value pairs.There is actually lots of differences which originate from first statement. They have separate top level interface, separate set of generic methods, different supported methods and different views of collection.


  Difference between Vector and ArrayList?

Lets note down the differences:-

(a). All the methods of Vector is synchronized. But, the methods of ArrayList is not synchronized.

(b). Vector is a Legacy class added in first release of JDK. ArrayList was part of JDK 1.2, when collection framework was introduced in java.

(c). By default, Vector doubles the size of its array when it is re-sized internally. But, ArrayList increases by half of its size when it is re-sized.


  Difference between TreeSet and SortedSet?

SortedSet is an interface which TreeSet implements. That' it !!


  Difference between ArrayList and LinkedList?

LinkedList store elements within a doubly-linked list data structure. ArrayList store elements within a dynamically resizing array.

LinkedListallows for constant-time insertions or removals, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list. ArrayLists,on the other hand, allow random access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap.

LinkedList has more memory overhead than ArrayList because in ArrayList each index only holds actual object (data) but in case of LinkedList each node holds both data and address of next and previous node.


  How to avoid ConcurrentModificationException while iterating a collection?

You should first try to find another alternative iterator which are fail-safe. For example if you are using List and you can use ListIterator. If it is legacy collection, you can use enumeration.

If above options are not possible then you can use one of three changes:-

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

2. You can convert the list to an array and then iterate on the array.

3. You can lock the list while iterating by putting it in a synchronized block.


  What is UnsupportedOperationException?

This exception is thrown on invoked methods which are not supported by actual collection type.

For example, if you make a read-only list list using "Collections.unmodifiableList(list)" and then call add() or remove() method, what should happen. It should clearly throw UnsupportedOperationException.


  Why there is not method like Iterator.add() to add elements to the collection?

The semantics are unclear, given that the contract for Iterator makes no guarantees about the order of iteration. Note, however, that ListIterator does provide an add operation, as it does guarantee the order of the iteration.


  What are different Collection views provided by Map interface?

Map interface provides three collection views:-

1. Set keySet(): Returns a Set view of the keys contained in this 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.

2. Collection values(): Returns a Collection view of the values contained in this 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.

3. Set Map.Entry(K,V) entrySet(): Returns a Set view of the mappings contained in this 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.


  How to decide between HashMap and TreeMap?

For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.


  While passing a Collection as argument to a function, how can we make sure the function will not be able to modify it?

We can create a read-only collection using Collections.unmodifiableCollection(Collection c) method before passing it as argument, this will make sure that any operation to change the collection will throw UnsupportedOperationException.


  How can we create a synchronized collection from given collection?

We can use Collections.synchronizedCollection(Collection c) to get a synchronized (thread-safe) collection backed by the specified collection.


  What are common algorithms implemented in Collections Framework?

Java Collections Framework provides algorithm implementations that are commonly used such as sorting and searching. Collections class contain these method implementations. Most of these algorithms work on List but some of them are applicable for all kinds of collections. Some of them are sorting, searching, shuffling, min-max values.


  What is Java Priority Queue?

PriorityQueue is an unbounded queue based on a priority heap and the elements are ordered in their natural order or we can provide Comparator for ordering at the time of creation. PriorityQueue doesn't allow null values and we can't add any object that doesn't provide natural ordering or we don't have any comparator for them for ordering. Java PriorityQueue is not thread-safe and provided O(log(n)) time for enqueing and dequeing operations. Check this post for java priority queue example.


  What are advantages of iterating a collection using iterator?

For loop does not allow updating the collection(add or remove) whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections implement Iterator interface.


  What is the difference between poll() and remove() method of Queue interface?

Though both poll() and remove() method from Queue is used to remove the object and returns the head of the queue, there is a subtle difference between them. If Queue is empty() then a call to remove() method will throw Exception, while a call to poll() method returns null. By the way, exactly which element is removed from the queue depends upon queue's ordering policy and varies between different implementation, for example, PriorityQueue keeps the lowest element as per Comparator or Comparable at head position.


  How do you remove an entry from a Collection? and subsequently what is the difference between the remove() method of Collection and remove() method of Iterator, which one you will use while removing elements during iteration?

Collection interface defines remove(Object obj) method to remove objects from Collection. List interface adds another method remove(int index), which is used to remove object at specific index. You can use any of these method to remove an entry from Collection, while not iterating. Things change, when you iterate.

Suppose you are traversing a List and removing only certain elements based on logic, then you need to use Iterator's remove() method. This method removes current element from Iterator's perspective. If you use Collection's or List's remove() method during iteration then your code will throw ConcurrentModificationException. That's why it's advised to use Iterator remove() method to remove objects from Collection.


  What do you need to do to use a custom object as a key in Collection classes like Map or Set?

If you are using any custom object in Map as key, you need to override equals() and hashCode() method, and make sure they follow their contract.

On the other hand if you are storing a custom object in Sorted Collection e.g. SortedSet or SortedMap, you also need to make sure that your equals() method is consistent to compareTo() method, otherwise that collection will not follow there contacts e.g. Set may allow duplicates.


  What is NavigableMap in Java? What is a benefit over Map?

NavigableMap Map was added in Java 1.6, it adds navigation capability to Map data structure. It provides methods like lowerKey() to get keys which is less than specified key, floorKey() to return keys which is less than or equal to specified key, ceilingKey() to get keys which is greater than or equal to specified key and higherKey() to return keys which is greater specified key from a Map.

It also provide similar methods to get entries e.g. lowerEntry(), floorEntry(), ceilingEntry() and higherEntry(). Apart from navigation methods, it also provides utilities to create sub-Map e.g. creating a Map from entries of an exsiting Map like tailMap, headMap and subMap. headMap() method returns a NavigableMap whose keys are less than specified, tailMap() returns a NavigableMap whose keys are greater than the specified and subMap() gives a NavigableMap between a range, specified by toKey to fromKey.


  Why insertion and deletion in ArrayList is slow compared to LinkedList ?

1. 1. ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array.

During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.


  What is a KeySet View ?

KeySet is a set returned by the keySet() method of the Map Interface, It is a set that contains all the keys present in the Map.


  Difference between ArrayList and Vector

ArrayList

1. ArrayList is NOT synchronized by default.

2. ArrayList can use only Iterator to access the elements.

3. The ArrayList increases its array size by 50 percent if it runs out of room.

4. ArrayList has no default size.

Vector

1. Vector List is synchronized by default.

2. Vector list can use Iterator and Enumeration Interface to access the elements.

3. A Vector defaults to doubling the size of its array if it runs out of room.

4. While vector has a default size of 10.


  Why are Iterators returned by ArrayList called Fail Fast ?

Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.


  How do you decide when to use ArrayList and When to use LinkedList?

If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection.

If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation.


  What is the Set interface ?

1. The Set interface provides methods for accessing the elements of a finite mathematical set

2. Sets do not allow duplicate elements

3. Contains no methods other than those inherited from Collection

4. It adds the restriction that duplicate elements are prohibited

5. Two Set objects are equal if they contain the same elements


  Difference between HashSet and TreeSet ?

HashSet

1. HashSet is under set interface i.e. it does not guarantee for either sorted order or sequence order.

2. We can add any type of elements to hash set.

TreeSet

1. TreeSet is under set i.e. it provides elements in a sorted order (acceding order).

2. We can add only similar types of elements to tree set.


  What is a Map ?

1. A map is an object that stores associations between keys and values (key/value pairs).

2. Given a key, you can find its value. Both keys and values are objects.

3. The keys must be unique, but the values may be duplicated.

4. Some maps can accept a null key and null values, others cannot.


  How do you decide when to use HashMap and when to use TreeMap ?

For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative.

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


  How does a Hashtable internally maintain the key-value pairs?

TreeMap actually implements the SortedMap interface which extends the Map interface.

In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.


  What is a Values Collection View ?

Values Collection View is a collection returned by the values() method of the Map Interface, It contains all the objects present as values in the map.


  What is an EntrySet View ?

Entry Set view is a set that is returned by the entrySet() method in the map and contains Objects of type Map. Entry each of which has both Key and Value.


  When to use ArrayList or LinkedList ?

Adding new elements is pretty fast for either type of list. For the ArrayList, doing random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow.

This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links.

So an ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.


PHP

PHP is a server-side scripting language designed primarily for web development but is also used as a general-purpose programming language..

Read more