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?
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?
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)
The insertion order is the order used to add the elements in the collection.
Iteration order for above implementations:
There are collection the could preserve the insertion order when you add an element, others cannot. Please refer at this link
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
.