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:
TreeSet is a particular Set, that keeps its elements in a naturally "sorted" order.LinkedHashSet is a particular Set, that does retain the insertion order.If you want to "order" your list, you'll have to do that manually:
Collections.sort(list);
In fact, by "sorting" a list, you will re-arrange all list element indexes. See the relevant Javadoc on Collections.sort()
When you say a List is ordered, it really just means that the lists preserve the order in which the element were inserted and the order in which they can be retrieved is predictable.
A Set is not ordered, its focus is just to have unique elements. A TreeSet is a SortedSet which along with maintaining uniqueness, also maintains elements in a sorted order. And hence the result that you see above
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With