1
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.

  • 1
    The fact that `Set` is unordered does not mean that it will iterate over its elements in a different, random order each time you iterate it. It returns the elements in a certain order (in this case AB, AC, A, AE, AD), but you just can't predict what the order is. – Jesper May 10 '19 at 10:50
  • It could be because the five strings you added happen to be bucketed in some order which the iterator happens to be using. But, this behavior is not guaranteed, and could vary on the JVM, and could change as you add/remove elements. Read [Iteration order of HashSet](https://stackoverflow.com/questions/2704597/iteration-order-of-hashset) for more information. – Tim Biegeleisen May 10 '19 at 10:52

2 Answers2

0

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

Nishant Modi
  • 669
  • 1
  • 6
  • 19
0

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.

Amit Bera
  • 7,075
  • 1
  • 19
  • 42