Arent Lists a Ordered Collection, and Sets arent ordered? Then Why does this program sorts the String in Alphabetical order with Sets but not Lists? I understand the duplicates parts of the two.
PrintStream out = System.out;
List<String> set = new ArrayList<String>();
String s = "ILLUSIONS";
for(int i = 0; i< s.length(); i++)
{
set.add((new Character(s.charAt(i))).toString());
}
out.println(set);
outputs: ILLUSIONS
PrintStream out = System.out;
Set<String> set = new TreeSet<String>();
String s = "ILLUSIONS";
for(int i = 0; i< s.length(); i++)
{
set.add((new Character(s.charAt(i))).toString());
}
out.println(set);
outputs: ILNOSU
Lists are “ordered” by element index. That means they retain the order of insertion of elements. Sets (in general) do not retain such an order. Some exceptions:
TreeSetis a particularSet, that keeps its elements in a naturally “sorted” order.LinkedHashSetis a particularSet, that does retain the insertion order.If you want to “order” your list, you’ll have to do that manually:
In fact, by “sorting” a list, you will re-arrange all list element indexes. See the relevant Javadoc on
Collections.sort()