Search code examples
javasetsetstring

Set<String> doesn't maintain order the same as the order the elements were added in


Edit: this is actually for an Android application, which means (as far as I know), I can only use a HashSet.

Set<String> set = new HashSet<String>();

set.add("1");
set.add("2");
set.add("3");
set.add("4");
set.add("5");
set.add("6");
set.add("7");
set.add("8");

String[] array = set.toArray(new String[0]); // convert the set to an array

System.out.println(Arrays.toString(array)); // test what the set looks like

The output of that is [3, 2, 1, 7, 6, 5, 4, 8]

I expected [1, 2, 3, 4, 5, 6, 7, 8] because I assumed it would add the Strings to the Set in order of when I added them.

In my application, it's essential that the order of the Set is in the order that the elements were added to the Set.

Is there any reason that this Set is out of order? Or is there a way to put it back into the order that the elements were added in?


Solution

  • Use a LinkedHashSet if you want to order the elements of the set. For more details, see this link.