Java Collections Quiz - MCQ - Multiple Choice Questions

This post contains a set of 50 multiple-choice questions covering various aspects of the Java Collections Framework, including classes, concurrent classes, and interfaces. Take this Java Collections Quiz to test your knowledge on Java collections framework.

1. Which interface represents a resizable array of objects in Java Collections?

a) Set
b) List
c) Map
d) Queue

Answer:

b) List

Explanation:

The List interface represents an ordered collection or sequence, and it is typically implemented by classes like ArrayList and LinkedList, which are resizable arrays of objects.

2. Which of these is not a method defined in the Map interface?

a) put()
b) get()
c) remove()
d) add()

Answer:

d) add()

Explanation:

The add() method is not defined in the Map interface. Map interface includes methods like put(), get(), and remove() for manipulating key-value pairs.

3. What is the primary difference between HashSet and TreeSet in Java Collections?

a) HashSet is ordered, while TreeSet is unordered
b) HashSet is faster than TreeSet
c) TreeSet maintains elements in a sorted order, while HashSet does not
d) TreeSet allows duplicate elements, while HashSet does not

Answer:

c) TreeSet maintains elements in a sorted order, while HashSet does not

Explanation:

The main difference between HashSet and TreeSet is that TreeSet maintains its elements in a sorted order (either natural ordering or according to a Comparator) while HashSet does not guarantee any order.

4. What type of collection does the java.util.Stack class represent?

a) Queue
b) Set
c) List
d) Map

Answer:

c) List

Explanation:

The Stack class extends Vector and represents a last-in-first-out (LIFO) stack of objects. Despite its name, it is a List implementation.

5. Which of these interfaces is not part of the Java Collections Framework?

a) List
b) SortedMap
c) SortedSet
d) Sortable

Answer:

d) Sortable

Explanation:

Sortable is not an interface in the Java Collections Framework. List, SortedMap, and SortedSet are all interfaces within the framework.

6. Which class is used to create a synchronized version of a Map?

a) ConcurrentHashMap
b) Collections.synchronizedMap()
c) Hashtable
d) SyncMap

Answer:

b) Collections.synchronizedMap()

Explanation:

Collections.synchronizedMap() method is used to return a synchronized (thread-safe) map backed by the specified map.

7. What is the purpose of the Comparable interface in Java Collections?

a) To define a natural ordering for objects of each class that implements it
b) To enable objects to be duplicated
c) To compare two different collections
d) To create a new type of collection

Answer:

a) To define a natural ordering for objects of each class that implements it

Explanation:

The Comparable interface is used to define a natural ordering for objects of each class that implements it. It has a compareTo method used for sorting objects.

8. Which of these collection classes does not allow duplicate elements?

a) ArrayList
b) HashSet
c) LinkedList
d) Vector

Answer:

b) HashSet

Explanation:

HashSet does not allow duplicate elements. It is a collection that does not store duplicate values.

9. What is the initial capacity of a HashMap in Java Collections Framework?

a) 10
b) 12
c) 16
d) 20

Answer:

c) 16

Explanation:

The default initial capacity of a HashMap is 16. This is the number of buckets in the hash table initially.

10. What exception is thrown when an object is not found in a PriorityQueue?

a) ObjectNotFoundException
b) NoSuchElementException
c) QueueException
d) ElementNotFoundException

Answer:

b) NoSuchElementException

Explanation:

NoSuchElementException is thrown if the PriorityQueue is empty and methods like remove() or element() are called.

11. Which of these classes implements a doubly-linked list in Java Collections?

a) ArrayList
b) LinkedList
c) Vector
d) HashSet

Answer:

b) LinkedList

Explanation:

LinkedList is the implementation of a doubly-linked list in the Java Collections Framework.

12. What is a major feature of the ConcurrentHashMap class?

a) It does not allow null values
b) It is not thread-safe
c) It allows the modification of the collection while iterating
d) It uses a single lock for the whole map

Answer:

c) It allows the modification of the collection while iterating

Explanation:

ConcurrentHashMap allows concurrent modification of the Map from several threads without the need to block them.

13. Which method in the Collections class is used to reverse the order of elements in a List?

a) reverseOrder()
b) reverse()
c) invert()
d) flip()

Answer:

b) reverse()

Explanation:

Collections.reverse() is used to reverse the order of elements in a List.

14. In which scenario would you use a WeakHashMap?

a) When you need to maintain a mapping for a short duration
b) When you need to store large objects
c) When keys can be garbage collected
d) When you need synchronized access to the map

Answer:

c) When keys can be garbage collected

Explanation:

WeakHashMap is a hashtable-based implementation where the keys are weak references, allowing the key-value pairs to be garbage-collected when the key is no longer in ordinary use.

15. What is the purpose of the Collections.unmodifiableCollection() method?

a) To create a new collection that is a clone of the current collection
b) To create a read-only view of a collection
c) To sort the collection in an unmodifiable order
d) To merge two collections into an unmodifiable collection

Answer:

b) To create a read-only view of a collection

Explanation:

Collections.unmodifiableCollection() method is used to return an unmodifiable view of the specified collection. This means that the collection cannot be modified through this view.

16. Which class should be used for a resizable array that provides the ability to grow or shrink its size dynamically?

a) LinkedList
b) Vector
c) ArrayList
d) ArrayDeque

Answer:

c) ArrayList

Explanation:

ArrayList is an implementation of the List interface that uses a resizable array, which is expanded or contracted as needed.

17. What is the primary difference between the offer() and add() methods in a Queue?

a) offer() throws an exception if the element cannot be added, while add() returns false
b) offer() and add() are identical in functionality
c) offer() returns false if the element cannot be added, while add() throws an exception
d) offer() is used in priority queues, while add() is used in normal queues

Answer:

c) offer() returns false if the element cannot be added, while add() throws an exception

Explanation:

In Queue, the offer() method is typically preferred over add() as it returns false if the element cannot be added due to capacity restrictions, while add() throws an IllegalStateException.

18. Which of these classes provides a fail-fast iterator?

a) CopyOnWriteArrayList
b) ConcurrentHashMap
c) ArrayList
d) ConcurrentLinkedQueue

Answer:

c) ArrayList

Explanation:

ArrayList provides a fail-fast iterator, which means it will throw a ConcurrentModificationException if the collection is modified after the iterator is created, except through the iterator's own remove method.

19. What is the behavior of the poll() method in a Queue when the Queue is empty?

a) Throws an exception
b) Returns null
c) Blocks until an element is available
d) Returns a default value

Answer:

b) Returns null

Explanation:

The poll() method retrieves and removes the head of the queue, or returns null if the queue is empty.

20. What is the key characteristic of a Set in Java Collections?

a) Allows duplicate elements
b) Maintains insertion order
c) Stores elements in key-value pairs
d) Does not allow duplicate elements

Answer:

d) Does not allow duplicate elements

Explanation:

A Set is a collection that does not allow duplicate elements. It models the mathematical set abstraction.

21. Which Java collection class is thread-safe and does not allow null elements?

a) ConcurrentHashMap
b) CopyOnWriteArrayList
c) Vector
d) Hashtable

Answer:

d) Hashtable

Explanation:

Hashtable is a legacy class from the original version of Java. It is synchronized (thread-safe) and does not allow null keys or null values.

22. Which method in the List interface allows to replace an element at a specific position?

a) set(int index, E element)
b) replace(int index, E element)
c) put(int index, E element)
d) change(int index, E element)

Answer:

a) set(int index, E element)

Explanation:

The set(int index, E element) method replaces the element at the specified position in the list with the specified element.

23. What type of collection is returned by Collections.synchronizedList()?

a) An unmodifiable collection
b) A synchronized (thread-safe) collection
c) A sorted collection
d) A collection that supports concurrent modification

Answer:

b) A synchronized (thread-safe) collection

Explanation:

Collections.synchronizedList() wraps a given List and returns a synchronized (thread-safe) version of it.

24. What is the primary difference between ConcurrentSkipListMap and TreeMap?

a) ConcurrentSkipListMap is synchronized, whereas TreeMap is not
b) TreeMap is faster than ConcurrentSkipListMap
c) ConcurrentSkipListMap allows null values, but TreeMap does not
d) TreeMap uses a hash table, while ConcurrentSkipListMap uses a skip list

Answer:

a) ConcurrentSkipListMap is synchronized, whereas TreeMap is not

Explanation:

ConcurrentSkipListMap is a concurrent, thread-safe version of a skip list, while TreeMap is a non-synchronized, sorted map implementation.

25. What does the iterator of a CopyOnWriteArrayList return when the list is modified after the iterator is created?

a) The updated list
b) The list at the state it was when the iterator was created
c) A ConcurrentModificationException
d) An UnsupportedOperationException

Answer:

b) The list at the state it was when the iterator was created

Explanation:

The iterator of a CopyOnWriteArrayList returns a "snapshot" of the list at the point the iterator was created, regardless of subsequent modifications.

26. Which Java collection is best suited for LIFO (Last-In-First-Out) operations?

a) ArrayList
b) LinkedList
c) ArrayDeque
d) PriorityQueue

Answer:

c) ArrayDeque

Explanation:

ArrayDeque is commonly used for stack operations and is more efficient than Stack. It provides a resizable array and allows null elements, making it suitable for LIFO operations.

27. What is the primary difference between Iterator and ListIterator?

a) Iterator allows traversing in both directions, whereas ListIterator only allows forward traversal
b) ListIterator allows traversing in both directions, whereas Iterator only allows forward traversal
c) Iterator can modify the collection, whereas ListIterator cannot
d) ListIterator can only be used with lists, whereas Iterator can be used with any collection

Answer:

b) ListIterator allows traversing in both directions, whereas Iterator only allows forward traversal

Explanation:

ListIterator extends Iterator with additional methods that allow bidirectional traversal of a list and the modification of elements.

28. What is the significance of the BlockingQueue interface in Java Collections?

a) It automatically sorts elements
b) It allows 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
c) It ensures that only unique elements are stored
d) It is used for managing concurrent data access

Answer:

b) It allows 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

Explanation:

BlockingQueue is designed for cases where producers and consumers are different threads. Consumers can wait for producers to insert items and vice-versa.

29. Which of these is not a feature of the LinkedHashMap class?

a) Maintains insertion order
b) Permits null elements
c) Is not synchronized
d) Consumes less memory than HashMap

Answer:

d) Consumes less memory than HashMap

Explanation:

LinkedHashMap consumes more memory than HashMap because it maintains a linked list to keep track of insertion order.

30. What is the behavior of the retainAll() method in the Collection interface?

a) It removes all the elements from the collection
b) It retains only those elements that are also contained in the specified collection
c) It adds a collection of elements to the existing collection
d) It compares two collections and returns true if they have the same elements

Answer:

b) It retains only those elements that are also contained in the specified collection

Explanation:

The retainAll() method is used to retain only the elements in the collection that are contained in the specified collection.

31. Which of these interfaces is typically used for a collection that does not allow duplicate elements and for which order is not an issue?

a) List
b) Set
c) Map
d) Queue

Answer:

b) Set

Explanation:

The Set interface models the mathematical set abstraction and is typically used for collections that do not allow duplicate elements and do not need to maintain any order.

32. What is the difference between the add and offer methods in the Queue interface?

a) There is no difference, both insert an element into the queue
b) add throws an exception if the element can't be added, while offer returns false
c) add returns false if the element can't be added, while offer throws an exception
d) offer is used in priority queues, while add is used in normal queues

Answer:

b) add throws an exception if the element can't be added, while offer returns false

Explanation:

In the Queue interface, the add method throws an IllegalStateException if the element cannot be added due to capacity restrictions, while the offer method returns false in such cases.

33. Which method would you use to obtain the first element of a Set?

a) getFirst()
b) first()
c) It's not possible to get the first element of a Set as it doesn't maintain any order
d) iterator().next()

Answer:

d) iterator().next()

Explanation:

Sets do not have a method to directly retrieve an element by its position because Sets typically do not guarantee an order. The iterator().next() method can be used to get the first element if iterating over the Set.

34. What does the Collections.synchronizedSet() method do?

a) Returns a synchronized (thread-safe) set backed by the specified set
b) Creates a new set that is a copy of the existing set
c) Sorts the given set
d) Merges two sets into a new set

Answer:

a) Returns a synchronized (thread-safe) set backed by the specified set

Explanation:

Collections.synchronizedSet() method is used to return a synchronized (thread-safe) set backed by the specified set.

35. Which class in Java Collections Framework is designed for cases where high-throughput and thread-safe implementation is required?

a) Vector
b) ArrayList
c) CopyOnWriteArrayList
d) LinkedList

Answer:

c) CopyOnWriteArrayList

Explanation:

CopyOnWriteArrayList is designed for environments where high-throughput is needed, and the array rarely changes but is frequently iterated. It provides a thread-safe variant of ArrayList.

36. What is the typical use of a PriorityBlockingQueue?

a) To implement a producer-consumer scenario where elements are processed based on priority
b) For multithreaded applications to sort elements
c) To block elements from entering the queue based on priority
d) To create a queue that holds elements of a single type

Answer:

a) To implement a producer-consumer scenario where elements are processed based on priority

Explanation:

PriorityBlockingQueue is a thread-safe priority queue implementation. It is used in scenarios where multi-threaded tasks need to process elements based on their priorities.

37. In Java Collections, what is the main difference between a HashMap and a Hashtable?

a) HashMap is synchronized, whereas Hashtable is not
b) Hashtable allows one null key, but HashMap does not
c) HashMap allows null keys and values, but Hashtable does not
d) There is no significant difference

Answer:

c) HashMap allows null keys and values, but Hashtable does not

Explanation:

HashMap allows null keys and null values, whereas Hashtable does not allow null keys or values and is synchronized.

38. Which interface should be used when you need a map and you wish to preserve the order of elements?

a) SortedMap
b) LinkedHashMap
c) TreeMap
d) ConcurrentHashMap

Answer:

b) LinkedHashMap

Explanation:

LinkedHashMap maintains a linked list of the entries in the map, in the order in which they were inserted. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

39. What is a key characteristic of the ConcurrentLinkedQueue class?

a) It is not thread-safe
b) It uses a linked list that allows insertion and removal at both ends
c) It allows concurrent modification from multiple threads without locking
d) It maintains the elements in natural order

Answer:

c) It allows concurrent modification from multiple threads without locking

Explanation:

ConcurrentLinkedQueue is a thread-safe queue based on linked nodes and supports concurrent access from multiple threads without locking.

40. What does the Collections.emptySet() method return?

a) A new, empty set instance
b) A null pointer
c) A set containing a single null element
d) An immutable empty set

Answer:

d) An immutable empty set

Explanation:

Collections.emptySet() returns a special immutable empty set. This set is serializable and no elements can be added to it.

41. In Java Collections, what is the difference between the poll() and remove() methods of Queue interface?

a) poll() retrieves and removes the head of the queue, remove() only retrieves but does not remove
b) poll() returns null if the queue is empty, remove() throws an exception
c) There is no difference, both methods do the same thing
d) remove() returns null if the queue is empty, poll() throws an exception

Answer:

b) poll() returns null if the queue is empty, remove() throws an exception

Explanation:

In Queue interface, poll() retrieves and removes the head of the queue, returning null if the queue is empty, whereas remove() retrieves and removes the head of the queue but throws an exception if the queue is empty.

42. What will happen if you try to sort a List that contains a null element?

a) NullPointerException
b) The list will be sorted and the null element will be placed at the beginning
c) The null element will be ignored during sorting
d) The list will be sorted and the null element will be placed at the end

Answer:

a) NullPointerException

Explanation:

Attempting to sort a list containing null elements will result in a NullPointerException because null cannot be compared with non-null elements.

43. Which interface extends Queue and supports operations at both ends?

a) Set
b) Deque
c) List
d) Map

Answer:

b) Deque

Explanation:

Deque (double-ended queue) extends Queue and allows elements to be added or removed from both ends.

44. Which class is best suited for a FIFO (First-In-First-Out) queue implementation?

a) LinkedList
b) PriorityQueue
c) ArrayDeque
d) Stack

Answer:

c) ArrayDeque

Explanation:

ArrayDeque is more efficient than LinkedList for new standard FIFO (first-in-first-out) queue operations.

45. Which method in the Map interface is used to retrieve all keys contained in the map?

a) values()
b) keySet()
c) entrySet()
d) getAllKeys()

Answer:

b) keySet()

Explanation:

The keySet() method in the Map interface is used to return a Set view of the keys contained in the map.

46. What is the difference between the size and capacity of an ArrayList?

a) Size and capacity are the same in an ArrayList
b) Size is the number of elements in the ArrayList, and capacity is the size of the array buffer
c) Size is the size of the array buffer, and capacity is the number of elements it can hold
d) There is no concept of capacity in an ArrayList

Answer:

b) Size is the number of elements in the ArrayList, and capacity is the size of the array buffer

Explanation:

In an ArrayList, the size is the number of elements currently in the list, while the capacity is the size of the array buffer inside the ArrayList, which can potentially hold more elements than the current size.

47. Which of these classes is synchronized and is designed for use in multithreaded contexts?

a) ArrayList
b) HashMap
c) ConcurrentHashMap
d) LinkedList

Answer:

c) ConcurrentHashMap

Explanation:

ConcurrentHashMap is a concurrent collection class that allows multiple threads to read and write concurrently and is designed to be used in multithreaded contexts.

48. What will Collections.max() return when applied to a Collection of Strings?

a) The first string in the collection
b) The string with the most characters
c) The string that comes last in lexicographical order
d) The string that comes first in lexicographical order

Answer:

c) The string that comes last in lexicographical order

Explanation:

Collections.max() returns the maximum element of the given collection, according to the natural ordering of its elements. For a string, it would be the one that comes last in lexicographical order.

49. Which interface is the root interface in the collection hierarchy?

a) List
b) Set
c) Collection
d) Map

Answer:

c) Collection

Explanation:

The Collection interface is the root interface of the Java Collections Framework. Most collections in Java are derived from this interface.

50. Which method do you need to implement when creating a class that can be used as a key in a HashMap?

a) compareTo()
b) equals() and hashCode()
c) clone()
d) toString()

Answer:

b) equals() and hashCode()

Explanation:

When creating a class that can be used as a key in a HashMap, it is crucial to properly override both equals() and hashCode() methods to ensure that duplicate keys are not allowed and the hashcode contract is maintained.


Comments