Java Programming - Objects and Collections - Discussion

Discussion Forum : Objects and Collections - General Questions (Q.No. 1)
1.
Suppose that you would like to create an instance of a new Map that has an iteration order that is the same as the iteration order of an existing instance of a Map. Which concrete implementation of the Map interface should be used for the new instance?
TreeMap
HashMap
LinkedHashMap
The answer depends on the implementation of the existing instance.
Answer: Option
Explanation:

The iteration order of a Collection is the order in which an iterator moves through the elements of the Collection. The iteration order of a LinkedHashMap is determined by the order in which elements are inserted.

When a new LinkedHashMap is created by passing a reference to an existing Collection to the constructor of a LinkedHashMap the Collection.addAll method will ultimately be invoked.

The addAll method uses an iterator to the existing Collection to iterate through the elements of the existing Collection and add each to the instance of the new LinkedHashMap.

Since the iteration order of the LinkedHashMap is determined by the order of insertion, the iteration order of the new LinkedHashMap must be the same as the interation order of the old Collection.

Discussion:
6 comments Page 1 of 1.

Vanessa said:   12 months ago
I don't understand why D is not the correct answer.

If the existing instance is a TreeMap then the iteration order will be the natural order of the keys. If the existing instance is a LinkedHashMap then the iteration order will be the order of insertion.

Surely, therefore it depends on the existing instance. If the existing instance is a TreeMap then you would want a TreeMap and if the existing instance is a LinkedHashMap you would want a LinkedHashMap.

Yami said:   2 years ago
In TreeMap, element insert in ascending order.

Sweta kumari said:   9 years ago
Why implementation of an existing object is not possible and why treemap is not right?

Mac said:   1 decade ago
@Amala.

TreeMap maintains natural sorted order not insertion order.

Ankit said:   1 decade ago
No in tree map iteration is done by the key value.

Amala said:   1 decade ago
Could someone explain why TreeMap is not right? Insertion order is maintained there too, right?

Post your comments here:

Your comments will be displayed after verification.