List<String> myList = new ArrayList<String>();
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
//Output is [A, B, C, D]
Set<String> mySet = new HashSet<String>();
mySet.add("A");
mySet.add("AB");
mySet.add("AC");
mySet.add("AD");
mySet.add("AE");
// Output is AB, AC, A, AE, AD
//Then I copy the set into another ArrayList and get this.
List<String> myList2 = new ArrayList<String>(mySet);
System.out.println(myList2);
//Output is [ AB, AC, A, AE, AD]
How come the order is the same? I know there is no way to predict the order of the myList2 since it was copied from a set, i wonder why the output is the same as the set.
Because Set is not ordered and List is ordered in nature, so the first list will return content in the same order you have inserted. but the second list which you have created have inserted items in order which was provided by Set which is random.
Hope this helps