Java - Interview Questions and Answers on Collections

Q1. Difference between TreeMap and HashMap ?show Answer

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 ?show Answer

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?show Answer

Ans. Java.util.Map

Q4. What is an Iterator?show Answer

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?show Answer

Ans. java.util.map

Q6. Difference between HashMap and Hashtable?show Answer

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 ?show Answer

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

Q8. What is the use of hashcode in Java ?show Answer

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 ?

show Answer

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

Q10. What is a Property class ?show Answer

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 ?show Answer

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");show Answer

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?show Answer

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 ?show Answer

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 ?show Answer

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?show Answer

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?show Answer

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?show Answer

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 ?show Answer

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 ?show Answer

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 ?show Answer

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 ?show Answer

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 ? show Answer

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?show Answer

Ans. LinkedHashMap

Q25. Is it legal to initialize List like this ?


LinkedList l=new LinkedList(); show Answer

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 ?show Answer

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 l=new LinkedList();
b. List l=new LinkedList();
c. LinkedList l=new LinkedList();
d. List l = new LinkedList();show Answer

Ans. c and d are correct.

Q28. What is comparator interface used for ?show Answer

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 ?show Answer

Ans. TreeSet and TreeMap

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

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

Q31. What is the difference between Collection and Collections ?show Answer

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

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

Ans. Using Collections.reverseOrder()

Map tree = new TreeMap(Collections.reverseOrder());

Q33. TreeMap orders the elements on which field ?show Answer

Ans. Keys

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

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 ?show Answer

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 ?show Answer

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 ?show Answer

Ans. No, results in exception.

Q38. Can value be null in TreeMap ?show Answer

Ans. Yes.

Q39. Which interface TreeMap implements ?show Answer

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

Q40. What is a ConcurrentHashMap ?show Answer

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 ?show Answer

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 ?show Answer

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 mySet = new HashSet();
mySet.add("4567");
mySet.add("5678");
mySet.add("6789");
for(String s: mySet){
System.out.println(s);
}
show Answer

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

Q44. What will be the output of this code ?

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

Ans. 4567
5678
6789

Q45. What will be the output of this code ?

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

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 mySet = new HashSet();
mySet.add(Day.MONDAY);
mySet.add(Day.SUNDAY);
mySet.add(Day.SATURDAY);

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

Ans. SUNDAY
MONDAY
SATURDAY

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

a. HashMap
b. TreeMap
c. LinkedHashMap
d. LinkedMap
show Answer

Ans. TreeMap


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

a. HashMap
b. TreeMap
c. LinkedHashMap
d. LinkedMap
show Answer

Ans. LinkedHashMap


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

a. Sorted Collection wont maintain them in any order.
b. Insertion Order
c. Order in which constants are declared.
d. Natural Sorting Order.
show Answer

Ans. Order in which constants are declared.


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

a. It will throw an exception.
b. It won't add the new Element without any exception.
c. The new element will replace the existing element.
d. Compiler will identify the problem and will throw an error.
show Answer

Ans. The new element will replace the existing element.


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

a. Random Order
b. Insertion Order
c. Natural Sorting Order
d. Inverse Natural Sorting Order
show Answer

Ans. Random Order


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

a. List
b. Set
c. Collection
d. Map
show Answer

Ans. Map


Q53. Which of the following is false ?

a. HashMap came before HashTable.
b. HashMap allows null values whereas Hashtable doesn’t allow null values.
c. HashTable and HashMap allow Key-Value pairs.
d. Hashtable is synchronized whereas HashMap is not.
show Answer

Ans. HashMap came before HashTable.


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

a. HashTable
b. HashMap
c. TreeMap
d. LinkedHashMap
show Answer

Ans. HashTable


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

a. Set
b. List
c. Map
d. Any Collection implementation
show Answer

Ans. List


Q56. Effective Java 6 , TreeMap implements ...

a. Map Interface
b. SortedMap Interface
c. NavigableMap Interface
d. SortedNavigableMap Interface
show Answer

Ans. SortedMap Interface


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

a. Set
b. List
c. Map
d. Queue
show Answer

Ans. Map