Java Collection Interview Question Answers

Q1: What is the Java Collection framework?

Collection is an object that represents a group of objects.Java Collections Framework provides a well designed set of interfaces and classes that support operations on a collections of objects.
Some of the benefits of collections framework are:
Reduced development effort by using core collection classes rather than implementing our own collection classes.
Code quality is enhanced with the use of well tested collections framework classes.
Reduced effort for code maintenance by using collection classes shipped with JDK.
Reusability and Interoperability

Q2: What are the basic interfaces of Java Collections Framework?

Collection is the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Java platform doesn’t provide any direct implementations of this interface.
Set:In mathematical concept, a set is just a group of unique items, in the sense that the group contains no duplicates. The Set interface extends the
Collection interface. Set does not allow duplicates in the collection. In Set implementations null is valid entry, but allowed only once.
List is an ordered collection and can contain duplicate elements. You can access any element from it’s index. List is more like array with dynamic length.
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.
Some other interfaces are Queue, Dequeue, Iterator, SortedSet, SortedMap and ListIterator.

Q3: What is the benefit of Generics in Collections Framework?

Generics came in java 1.5 and it allow us to provide the type of Object that a collection can contain, so if we try to add any element of other type it throws compile time error. With this it avoids ClassCastException at Runtime because you will get the error at compilation.

Q4: Why do we need wrapper classes?

It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types.
And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes.
Since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection.
Also we can pass them around as method parameters where a method expects an object.

Q5: Why Map interface doesn’t extend Collection interface?

Map doesn’t come under collection because the way it stores elements is different from collections. It stores in the form of key,value pair.

Q6: What is difference between Enumeration and Iterator interface?

With iterator one can remove element from collection using remove method which is not possible using Enumeration. Iterator denies the other thread to modify the collection object which is being iterated.

Q7: How can Arraylist be synchronized without using Vector?

Arraylist can be synchronized using: Collection.synchronizedList(List list)

Q8: What is difference between Arrays and ArrayList ?

Array size is fixed whereas arraylist is dynamic.
Array can be multidimensional whereas arraylist is one dimensional.
Array can have single data type object whereas arraylist can have single data type object if generics is used else it can be heterogeneous.

Q9: What is different between Iterator and ListIterator?

Iterator can be used to traverse in one forward direction whereas List can be used to traverse both ways forward and backward.
ListIterator as the name suggest, only used to traverse lists, whereas iterator can be used to traverse sets, lists.
ListIterator provides some extra functionality of adding and element, replacing an element, getting index of previous and next element.

Q10: What is difference between fail-fast and fail-safe?

Fail-fast iterator fails when some failure condition is observed and it is observed every iteration. In multithreaded scenario if we one thread is modifying the collection and another thread iterating over that collection then exception (ConcurrentModificationException) will be thrown. Example for fail fast is iterator from hashmap.
Fail Safe iterator doesn’t fail if collection gets modified because it works on clone of the collection not the original one. Example for this is iterator from ConcurrentHashMap

Q11: How HashMap works in Java?

HashMap stores data in key-value pair and works on hashing algorithm and uses hashCode() and equals() method for put and get methods.
When we call put method by passing key-value pair, HashMap uses Key hashCode() with hashing to find out the bucket index to store the key-value pair. Further in bucket, data get stored in LinkedList. Before storing it checks if key already exist then it overwrites the previous value. If key not found then it simply stress the key value pair. When we call get method by passing Key, it calls the hashCode() to find the bucket index and then use equals() method to find the correct Entry and return it’s value.

Q12: What is the importance of hashCode() and equals() methods?

They are the method getting used in hashing collections like hashset,hashmap etc. hashCode method gets called whenever we are putting or getting any element from collection to find the bucket index.
Once the index found then equals() will get called to check the equality of the element we are searching for or the key value pair we are putting in collection. For getting it check if passed key matches with anyone in the bucket and then return value accordingly. For putting it checks if passed key already exist in the bucket then overwrites the values.

Q13: What is Comparable and Comparator interface?

These are the two interfaces which need to be implemented by class whose objects are stored in a collection and that collection needs to be sorted on some sort of property of the class.
Comparable interface has method compareTo(Object). We need to implement the same in the class. And it should be implemented in such a way that it should return some sort of positive, negative or zero integer value.
Comparator interface has method compare(Object1,Object2). With comparable interface we can do sorting on one particular property of the objects. So to allow sorting with all different property of the objects Comparator comes into picture. Suppose If we have object of Employee class which has property like id,name,city etc. And we may need to sort on the basis of id or name or city. Then we can create different comparator object and pass them in Collections.sort() method to get collection sorted on the basis of specific property.

Q14: How to make collection unmodifiable?

Using Collections.unmodifiableCollection we can do this. And after applying this operation if we try to modify the collection then it throws UnsupportedOperationException.

Q15: How to create synchronized collection?

Using Collections.synchronizedCollection.

Q16: 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.

Q17: 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.

Q18: How to convert an array of String to arraylist?

Collections class provides some static functions to perform specific operations on collection types. And Arrays provide utility functions to be performed on array types.
e.g String[] alps = {"a", "b", "c", "d", "e"};
List alpsList = Arrays.asList(alps);

Q19: Can you make List,Set and Map elements synchronized?

Yes, Collections class provides methods to make List,Set or Map elements as synchronized:
synchronizedList(List l){}
synchronizedSet(Set s){}
synchronizedSortedSet(SortedSet s){}
synchronizedMap(Map m){}
synchronizedSortedMap(SortedMap m){}

Q20: Why we use Map interface? What are main classes implementing Map interface?

Map interface is a special type of collection which is used to store key-value pairs. It does not extend Collection interface for this reason. This interface provides methods to add, remove, search or iterate over various views of Map.
Main classes implementing Map interface are: HashMap, Hashtable, EnumMap, IdentityHashMap, LinkedHashMap and Properties.

Q21: What is the between Hashtable and HashMap?

Both provide key-value access to data. The key differences are :
a. Hashtable is synchronised but HasMap is not synchronised.
b. HashMap permits null values but Hashtable doent allow null values.
c. iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not fail safe.

Q22: What are different Collection views provided by Map interface?

Map interface provides 3 views of key-values pairs stored in it:
key set view
value set view
entry set view
All the views can be navigated using iterators.

Q23: What is difference between ArrayList and vector?

Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block, thus making Vector class thread-safe.
Size growth - Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
Performance - Since vector is thread-safe, the performance is slower than ArrayList.

Q24: Why it is preferred to write List str = new ArrayList instead of ArrayList str = new ArrayList?

It is preferred to make the code more flexible like if we have any method which accepts list outPutList(List list) then we can call this by passing any sub type like arraylist,vector or linkedlist.

Q25: What is ConcurrentHashmap?

ConcurrentHashMap is thread safe implementation of Map. It is divided into multiple numbers of segments and the default is 16 on initialization which means it allows 16 threads to work on concurrently on a specific segment. It’s put and remove method is synchronized but get is not. So fetching element doesn’t lock it. It doesn’t allow NULL as key or value. Key is used to locate the segment index and then the actual bucket in that segment.

Q26: Can multiple threads read from a given Hashtable concurrently ?

No, get() method of hash table is synchronized (even for synchronized HashMap).

Q27: What is IdentityHashMap?

It is similar to Hashmap excepts it checks equality of elements using references instead of values.

Q28: What is the importance of hashCode() and equals() methods?

HashMap uses Key object hashCode() and equals() method to determine the index to put the key-value pair. These methods are also used when we try to get value from HashMap. If these methods are not implemented correctly, two different Key’s might produce same hashCode() and equals() output and in that case rather than storing it at different location, HashMap will consider them same and overwrite them.
Similarly all the collection classes that doesn’t store duplicate data use hashCode() and equals() to find duplicates, so it’s very important to implement them correctly. The implementation of equals() and hashCode() should follow these rules.
If o1.equals(o2), then o1.hashCode() == o2.hashCode()should always be true.
If o1.hashCode() == o2.hashCode is true, it doesn’t mean that o1.equals(o2) will be true.