Java TreeMap MCQ Questions and Answers

1. What is a TreeMap in Java?

a) A dynamic array structure
b) A hash table implementation
c) A map based on a tree structure
d) A linked list of key-value pairs

Answer:

c) A map based on a tree structure

Explanation:

TreeMap is a Map implementation that uses a Red-Black tree, providing a sorted map.

2. How are the keys in a TreeMap stored?

a) In random order
b) In insertion order
c) In ascending order
d) In descending order

Answer:

c) In ascending order

Explanation:

TreeMap stores its keys in ascending order, according to the natural ordering of its keys.

3. Can a TreeMap contain duplicate keys?

a) Yes
b) No
c) Only if they are strings
d) Only if they are numbers

Answer:

b) No

Explanation:

TreeMap cannot contain duplicate keys. Each key can map to exactly one value.

4. Which interface must the keys in a TreeMap implement?

a) Serializable
b) Cloneable
c) Comparable or Comparator
d) Iterable

Answer:

c) Comparable or Comparator

Explanation:

The keys in a TreeMap must implement the Comparable interface or be used with a Comparator to determine their order.

5. What happens when a null key is inserted into a TreeMap?

a) It is placed at the start
b) It is placed at the end
c) A NullPointerException is thrown
d) It replaces the smallest key

Answer:

c) A NullPointerException is thrown

Explanation:

Inserting a null key into a TreeMap will result in a NullPointerException, as TreeMap relies on natural ordering or comparators.

6. What method do you use to get all keys from a TreeMap?

a) getKeys()
b) keySet()
c) keys()
d) getAllKeys()

Answer:

b) keySet()

Explanation:

The keySet() method returns a set view of the keys contained in the TreeMap.

7. How do you retrieve the first key in a TreeMap?

a) getFirstKey()
b) firstKey()
c) topKey()
d) headKey()

Answer:

b) firstKey()

Explanation:

The firstKey() method retrieves the first (lowest) key currently in the TreeMap.

8. What is the default initial capacity of a TreeMap?

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

Answer:

d) 16

Explanation:

TreeMap does not have an initial capacity like HashMap because it's based on a Red-Black tree structure.

9. Can you store a null value in a TreeMap?

a) Yes
b) No
c) Only one null value
d) Only as the first entry

Answer:

a) Yes

Explanation:

TreeMap allows null values, but it does not support null keys.

10. How does TreeMap compare keys for sorting?

a) By hashcode
b) By natural ordering or a specified Comparator
c) Alphabetically
d) By length of key

Answer:

b) By natural ordering or a specified Comparator

Explanation:

TreeMap compares keys either by their natural ordering or by a specified Comparator at the time of TreeMap creation.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top