Java - Interview Questions and Answers on Collections

Q1.  Difference between TreeMap and HashMap ?

Ans. They are different the way they are stored in memory. TreeMap stores the Keys in order whereas HashMap stores the key value pairs randomly. 

Q2.  What is the difference between List, Set and Map ?

Ans. List - Members are stored in sequence in memory and can be accessed through index. 
Set - There is no relevance of sequence and index. Sets doesn't contain duplicates whereas multiset can have duplicates. Map - Contains Key , Value pairs.

Q3.  Which interface does java.util.Hashtable implement?

Ans. Java.util.Map

Q4.  What is an Iterator?

Ans. Iterator is an interface that provides methods to iterate over any Collection. 

Q5.  Which interface provides the capability to store objects using a key-value pair?

Ans. java.util.map

Q6.  Difference between HashMap and Hashtable?

Ans. Hashtable is synchronized whereas HashMap is not.

HashMap allows null values whereas Hashtable doesn’t allow null values.




Q7.  can we create a null as a key for a map collection ?

Ans. Yes , for Hashtable. Hashtable implements Map interface.

Q8.  What is the use of hashcode in Java ?

Ans. Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc. The value received from hashcode() is used as bucket number for storing elements. This bucket number is the address of the element inside the set/map. when you do contains() then it will take the hashcode of the element, then look for the bucket where hashcode points to and if more than 1 element is found in the same bucket (multiple objects can have the same hashcode) then it uses the equals() method to evaluate if object are equal, and then decide if contain() is true or false, or decide if element could be added in the set or not.

Q9.  Difference between Map and HashMap ?



Ans. Map is an interface where HashMap is the concrete class.

Q10.  What is a Property class ?

Ans. The properties class is a subclass of Hashtable that can be read from or written to a stream.

Q11.  what is the difference between collections class vs collections interface ?

Ans. Collections class is a utility class having static methods for doing operations on objects of classes which implement the Collection interface. For example, Collections has methods for finding the max element in a Collection.

Q12.  Will this code give error if i try to add two heterogeneous elements in the arraylist. ? and Why ?

List list1 = new ArrayList<>();
list1.add(5);
list1.add("5");

Ans. If we don't declare the list to be of specific type, it treats it as list of objects.

int 1 is auto boxed to Integer and "1" is String and hence both are objects.

Q13.  What is the difference between comparable and comparator in java.util pkg?

Ans. Comparable interface is used for single sequence sorting i.e.sorting the objects based on single data member where as comparator interface is used to sort the object based on multiple data members.

Q14.  Advantage of Collection classes over Arrays ?

Ans. Collections are re-sizable in nature. We can increase or decrease the size as per recruitment.
Collections can hold both homogeneous and heterogeneous data's.
Every collection follows some standard data structures.
Collection provides many useful built in methods for traversing,sorting and search. 

Q15.  What are the Disadvantages of using Collection Classes over Arrays ?

Ans. Collections can only hold objects, It can't hold primitive data types.

Collections have performance overheads as they deal with objects and offer dynamic memory expansion. This dynamic expansion could be a bigger overhead if the collection class needs consecutive memory location like Vectors.

Collections doesn't allow modification while traversal as it may lead to concurrentModificationException.


Q16.  What is Comparable Interface?

Ans. It is used to sort collections and arrays of objects using the collections.sort() and java.utils. The objects of the class implementing the Comparable interface can be ordered.


Q17.  Explain Set Interface?

Ans. It is a collection of element which cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.


Q18.  What is the difference between the size and capacity of a Vector?

Ans. The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time.


Q19.  Can we use Ordered Set for performing Binary Search ?

Ans. We need to access values on the basis of an index in Binary search which is not possible with Sets.

Q20.  Difference between ArrayList and LinkedList ?

Ans. LinkedList and ArrayList are two different implementations of the List interface. LinkedList implements it with a doubly-linked list. ArrayList implements it with a dynamically resizing array.

Q21.  If you are given a choice to use either ArrayList and LinkedList, Which one would you use and Why ?

Ans. ArrayList are implemented in memory as arrays and hence allows fast retrieval through indices but are costly if new elements are to be inserted in between other elements. 

LinkedList allows for constant-time insertions or removals using iterators, but only sequential access of elements 

1. Retrieval - If Elements are to be retrieved sequentially only, Linked List is preferred.
2. Insertion - If new Elements are to be inserted in between other elements , Array List is preferred.
3. Search - Binary Search and other optimized way of searching is not possible on Linked List.
4. Sorting - Initial sorting could be pain but lateral addition of elements in a sorted list is good with linked list.
5. Adding Elements - If sufficiently large elements needs to be added very frequently ,Linked List is preferable as elements don't need consecutive memory location.


Q22.  What are the pre-requisite for the collection to perform Binary Search ?

Ans. 1. Collection should have an index for random access.
2. Collection should have ordered elements.

Q23.  Can you provide some implementation of a Dictionary having large number of words ? 

Ans. Simplest implementation we can have is a List wherein we can place ordered words and hence can perform Binary Search.

Other implementation with better search performance is to use HashMap with key as first character of the word and value as a LinkedList.

Further level up, we can have linked Hashmaps like ,

hashmap {
a ( key ) -> hashmap (key-aa , value (hashmap(key-aaa,value)
b ( key ) -> hashmap (key-ba , value (hashmap(key-baa,value)
....................................................................................
z( key ) -> hashmap (key-za , value (hashmap(key-zaa,value)
}

upto n levels ( where n is the average size of the word in dictionary.


Q24.  Which Java collection class can be used to maintain the entries in the order in which they were last accessed?

Ans. LinkedHashMap

Q25.  Is it legal to initialize List like this ?


LinkedList<Integer> l=new LinkedList<int>(); 

Ans. No, Generic parameters cannot be primitives.

Q26.  Can we add duplicate keys in a HashMap ? What will happen if we attempt to add duplicate values ?

Ans. No, We cannot have duplicate keys in HashMap. If we attempt to do so , the previous value for the key is overwritten.

Q27.  Which of the following syntax are correct ?

a. LinkedList<Integer> l=new LinkedList<int>();
b. List<Integer> l=new LinkedList<int>();
c. LinkedList<Integer> l=new LinkedList<Integer>();
d. List<Integer> l = new LinkedList<Integer>();

Ans. c and d are correct.

Q28.  What is comparator interface used for ?

Ans. The purpose of comparator interface is to compare objects of the same class to identify the sorting order. Sorted Collection Classes ( TreeSet, TreeMap ) have been designed such to look for this method to identify the sorting order, that is why class need to implement Comparator interface to qualify its objects to be part of Sorted Collections.

Q29.  Which are the sorted collections ?

Ans. TreeSet and TreeMap

Q30.  What is rule regarding overriding equals and hasCode method ?

Ans. A Class must override the hashCode method if its overriding the equals method.

Q31.  What is the difference between Collection and Collections ?

Ans. Collection is an interface whereas Collections is a utility class.

Q32.  How can we reverse the order in the TreeMap ?

Ans. Using Collections.reverseOrder()

Map<Float,Integer> tree = new TreeMap<Float,Integer>(Collections.reverseOrder());

Q33.  TreeMap orders the elements on which field ?

Ans. Keys

Q34.  How TreeMap orders the elements if the Key is a String ?

Ans. As String implements Comparable, It refers to the String compareTo method to identify the order relationship among those elements.

Q35.  Can we add heterogeneous elements into TreeMap ?

Ans. No, Sorted collections don't allow addition of heterogeneous elements as they are not comparable. 

Q36.  Will it create any problem if We add elements with key as user defined object into the TreeMap ?

Ans. It won't create any problem if the objects are comparable i.e we have that class implementing Comparable interface.

Q37.  Can we null keys in TreeMap ?

Ans. No, results in exception.

Q38.  Can value be null in TreeMap ?

Ans. Yes.

Q39.  Which interface TreeMap implements ?

Ans. TreeMap implements NavigableMap, SortedMap, Serializable and Clonable.

Q40.  What is a ConcurrentHashMap ?

Ans. ConcurrentHashMap is a hashMap that allows concurrent modifications from multiple threads as there can be multiple locks on the same hashmap.

Q41.  What is the difference between ArrayList and LinkedList ?

Ans. Underlying data structure for ArrayList is Array whereas LinkedList is the linked list and hence have following differences -

1. ArrayList needs continuous memory locations and hence need to be moved to a bigger space if new elements are to be added to a filled array which is not required for LinkedList.

2. Removal and Insertion at specific place in ArrayList requires moving all elements and hence leads to O(n) insertions and removal whereas its constant O(1) for LinkedList.

3. Random access using index in ArrayList is faster than LinkedList which requires traversing the complete list through references.

4. Though Linear Search takes Similar Time for both, Binary Search using LinkedList requires creating new Model called Binary Search Tree which is slower but offers constant time insertion and deletion.

5. For a set of integers you want to sort using quicksort, it's probably faster to use an array; for a set of large structures you want to sort using selection sort, a linked list will be faster.   

Q42.  If I try to add Enum constants to a TreeSet, What sorting order will it use ?

Ans. Tree Set will sort the Values in the order in which Enum constants are declared.

Q43.  What will be the output of this code ?

Set<String> mySet = new HashSet<String>();
mySet.add("4567");
mySet.add("5678");
mySet.add("6789");
for(String s: mySet){
    System.out.println(s);
}


Ans. It will print 4567,5678 and 6789 but Order cannot be predicted.

Q44.  What will be the output of this code ?

Set<String> mySet = new TreeSet<String>();
mySet.add("4567");
mySet.add("5678");
mySet.add("6789");
for(String s: mySet){
    System.out.println(s);
}

Ans. 4567
5678
6789

Q45.  What will be the output of this code ?

Set<String> mySet = new HashSet<String>();
mySet.add("4567");
mySet.add("5678");
mySet.add("6789");
System.out.println(s.get(0));


Ans. This will give compile time error as we cannot retrieve the element from a specified index using Set. Set doesn't maintain elements in any order. 

Q46.  public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

public class Test {
    Set<Day> mySet = new HashSet<Day>();
    mySet.add(Day.MONDAY);
    mySet.add(Day.SUNDAY);
    mySet.add(Day.SATURDAY);

    for(Day d: mySet){
        System.out.println(d);
    }
}

Ans. SUNDAY
MONDAY
SATURDAY

Q47.  How is HashSet maintained in memory by Java ?

Ans. HashSet is maintained as HashMap by Java with values of the HashSet as Keys of the HashMap and value of the HashMap as the constant PRESENT.

Q48.  What is ConcurrentLinkedDeque ?

Ans. It's a Collections concrete class that provides implementation of  a Double Ended queue that allows  concurrent insertion, removal, and access operations that can be executed safely across multiple threads.

Q49.  What is CopyOnWriteArrayList ?

Ans. Its a type of ArrayList in which all Write operations , i.e add and set are performed by creating a new copy. This array never changes during the lifetime of the iterator, so it never throws ConcurrentModificationException

Q50.  What are the advantages and disadvantages of CopyOnWriteArrayList ?

Ans. This collections class has been implemented in such a manner that it can never throw ConcurrentModificationException. 

As it performs update and write operations by creating a new copy of ArrayList, It's slower compared to ArrayList.

Q51.  Name few Concurrent Collection Classes ?

Ans. ConcurrentHashMap
ConcurrentLinkedDeque
ConcurrentLinkedQueue
ConcurrentMap
ConcurrentNavigableMap
ConcurrentSkipListMap
ConcurrentSkipListSet

Q52.  Name few Collections Map implementations ?

Ans. AbstractMap
ConcurrentHashMap
ConcurrentSkipListMap
EnumMap
HashMap
IdentityHashMap
LinkedHashMap
SystemFlavorMap
TreeMap
WeakHashMap

Q53.  Which of the following collection maintain its elements in Natural Sorted order ? 

Ans. TreeMap


Q54.  Which of the following collections stores its elements in insertion Order ?

Ans. LinkedHashMap


Q55.  If we add Enum constants to a sorted collection ( Treemap , TreeSet ), What will be the order in which they will be maintained ?

Ans. Order in which constants are declared.


Q56.  If we try to add duplicate key to the HashMap, What will happen ?

Ans. The new element will replace the existing element.


Q57.  In what order the elements of a HashSet are retrieved ?

Ans. Random Order


Q58.  Which interface does java.util.Hashtable implement ?

Ans. Map


Q59.  Which of the following is false ?

Ans. HashMap came before HashTable.


Q60.  Which of the collections allows null as the key ?

Ans. HashTable


Q61.  Collections.sort can only be performed on ..

Ans. List


Q62.  Effective Java 6 , TreeMap implements ...

Ans. SortedMap Interface


Q63.  Which of the following doesn't extend Collection interface ?

Ans. Map


Q64. Which is the Parent Class of  Deque<E> class?

Ans.Iterable


Q65. Which is the Parent Class of HashMap class?

Ans.AbstractMap


Q66. Which is the Parent Class of PrinterStateReasons class?

Ans.HashMap


Q67. Which is the Parent Class of EnumSet class?

Ans.AbstractSet


Q68. Which interfaces are implemented by HashMap?

Ans.[Serializable,  Map,  Cloneable]


Q69. Name few classes that implement Collection interface?

Ans.[ Vector,  HashSet,  ConcurrentLinkedDeque,  ArrayBlockingQueue, AbstractCollection,  ConcurrentSkipListSet,  LinkedTransferQueue,  TreeSet,  ConcurrentLinkedQueue,  PriorityBlockingQueue,  AbstractList,  LinkedList,  ArrayDeque,  BeanContextServicesSupport,  LinkedBlockingQueue,  Stack,  EnumSet,  CopyOnWriteArraySet,  LinkedHashSet,  AttributeList,  SynchronousQueue,  RoleUnresolvedList,  RoleList,  DelayQueue,  PriorityQueue,  ArrayList,  AbstractQueue,  AbstractSequentialList,  JobStateReasons,  BeanContextSupport,  CopyOnWriteArrayList,  LinkedBlockingDeque,  AbstractSet]

Q70. Which is the Parent Class of AbstractSequentialList class?

Ans.AbstractList


Q71. Which is the Parent Class of LinkedHashSet class?

Ans.HashSet


Q72. Which interfaces are implemented by  ConcurrentSkipListSet?

Ans.[Collection]


Q73. Which interfaces are implemented by EnumSet?

Ans.[Serializable,  Iterable<E>,  Collection<E>,  Cloneable,  Set<E>]


Q74. Which is the Parent Class of  List<E> class?

Ans.Collection


Q75. Which interfaces are implemented by PrinterStateReasons?

Ans.[ PrintServiceAttribute, Serializable, Severity>,  Attribute,  Cloneable,  Map<PrinterStateReason]


Q76. Which interfaces are implemented by LinkedHashSet?

Ans.[Serializable,  Iterable<E>,  Collection<E>,  Cloneable,  Set<E>]


Q77. Which is the Parent Class of LinkedList class?

Ans.AbstractSequentialList


Q78. Which interfaces are implemented by LinkedList?

Ans.[ List<E>,  Collection<E>, Iterable<E>]


Q79. Which interfaces are implemented by AbstractSequentialList?

Ans.[ List<E>,  Collection<E>, Iterable<E>]


Q80. Which interfaces are implemented by  AbstractQueue?

Ans.[ Collection<E>, Iterable<E>]


Q81. Which is the Parent Class of  AbstractQueue class?

Ans.AbstractCollection


Q82. Which is the Parent Class of  SortedSet<E> class?

Ans.Set