What does it mean by "Insertion Order is preserved in Collections"?
Solution 1
Insertion Order means the order in which we are inserting the data.
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("alpha");
list.add("beta");
list.add("gamma");
for (String string : list) {
System.out.println(string);
}
}
Output : alpha beta gamma
Insertion order is maintained.
If you want the original insertion order there are the Linked
XXX
classes, which maintain an additional linked list in insertion order. Most of the time you don't care, so you use a HashXXX
, or if you want a natural order, so you use TreeXXX
.
Solution 2
Insertion order refers to the order in which you are adding elements to the data structure (i.e., a collection like List
, Set
, Map
, etc..).
For example, a List
object maintains the order in which you are adding elements, whereas a Set
object doesn't maintain the order of the elements in which they are inserted.
First, take a List
object and add elements:
List<String> list = new ArrayList<>();
list.add("1Z");
list.add("2Y");
list.add("3X");
System.out.println(list);
Output (i.e., objects inside List
): [1Z, 2Y, 3X] (order same as the insertion)
Now, take a Set
object:
Set<String> set = new HashSet<>();
set.add("1Z");
set.add("2Y");
set.add("3X");
System.out.println(set);
Output (i.e., objects inside Set
): [3X, 2Y, 1Z] (order disturbed)
Solution 3
The insertion order is the order used to add the elements in the collection.
Iteration order for above implementations:
- HashSet - undefined.
- HashMap - undefined
- LinkedHashSet - insertion order
- LinkedHashMap - insertion order of keys (by default), or 'access order'
- ArrayList - insertion order.
- LinkedList - insertion order.
- TreeSet - ascending order, according to Comparable / Comparator.
There are collection the could preserve the insertion order when you add an element, others cannot. Please refer at this link
Related videos on Youtube
Shashi
Updated on June 04, 2022Comments
-
Shashi almost 2 years
If we want to represent a group of individual objects where duplicates are allowed and insertion order is preserved, then we should go for List.
Here, what does insertion order refers to?
-
David about 7 yearsThe order in which elements are added to the list is the order in which they are retrieved from the list.
-
freedev about 7 yearsPossible duplicate of Collection that will maintain insertion order and no duplicates
-
flakes about 7 yearsSay you're trying to represent a line-up in a store. You want to make sure that you remember what order customers entered the line, so they can be served in that order. In this scenario you would need a collection where insertion order is preserved.
-
Vishy about 7 yearsThe order you inserted the elements can be retrieved by iterating over the elements.
-