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.

2 Answers

0
Nishant Modi On

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

0
Amit Bera On

The Set is unordered does not mean it will change the order time to time if there is no structural modification happen. If you insert some element in the Set and after that loop over it n times then you will get the same order for loop-1 to loop-n.

Set<String> mySet = new HashSet<String>();
mySet.add("A");
mySet.add("AB");
mySet.add("AC");
mySet.add("AD");
mySet.add("AE");
//print it 5 times it will print in the same order for all 5
System.out.println(mySet); // print line-1
System.out.println(mySet); // print line-2
System.out.println(mySet); // print line-3
System.out.println(mySet); // print line-4
System.out.println(mySet);// print line-5

So, you should not expect that order at line-1 and order at line-5 will be different.