Multiple choice java

Which collection class allows you to access its elements by associating a key with an element's value, and provides synchronization?

  1. java.util.SortedMap

  2. java.util.TreeMap

  3. java.util.TreeSet

  4. java.util.Hashtable

Reveal answer Fill a bubble to check yourself
D Correct answer
Explanation

To solve this question, the user needs to have a basic understanding of Java collections and their functionalities. Specifically, they need to be familiar with the concept of accessing elements by associating a key with a value and the concept of synchronization in Java collections.

Now, let's go through each option and explain why it is right or wrong:

A. java.util.SortedMap: This option is incorrect. While a SortedMap allows you to access its elements by associating a key with an element's value, it does not provide synchronization. To ensure thread-safe access to a SortedMap, you would need to use additional synchronization mechanisms such as the Collections.synchronizedSortedMap() method.

B. java.util.TreeMap: This option is incorrect. Although a TreeMap allows you to access its elements by associating a key with an element's value, it does not inherently provide synchronization. To achieve synchronized access to a TreeMap, you would need to use additional synchronization mechanisms such as the Collections.synchronizedSortedMap() method.

C. java.util.TreeSet: This option is incorrect. A TreeSet is not a collection class that allows you to access elements by associating a key with an element's value. It is an implementation of the Set interface that stores elements in a sorted and unique order.

D. java.util.Hashtable: This option is correct. Hashtable is a collection class in Java that allows you to access its elements by associating a key with an element's value. It also provides synchronization, meaning that multiple threads can safely access and modify the Hashtable concurrently without causing data inconsistency or other concurrency issues.

Therefore, the correct answer is:

The Answer is: D. java.util.Hashtable

AI explanation

java.util.Hashtable is a legacy key-value collection whose methods are all synchronized, making it thread-safe out of the box. java.util.TreeMap (and the SortedMap interface it implements) gives key-based access sorted by key but is not synchronized. java.util.TreeSet is a Set, not a key-value map, and is also unsynchronized. Since the question needs both key-based element access AND built-in synchronization, Hashtable is the only match — HashMap would give the mapping but not thread-safety.