Set vs alphabetical order in Java list
•
Java
Arent lists ordered collections and is not ordered? So why does this program sort strings alphabetically instead of lists? I understand the repetition 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);
Output: 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);
Output: ilnosu
Solution
The list is "sorted" by element index This means that they retain the order in which elements are inserted Collections (usually) do not retain this order Some exceptions:
>TreeSet is a special set that maintains its elements in a natural "sort" order. > Linkedhashset is a specific set that does preserve the insertion order
If you want to "order" your list, you must do this manually:
Collections.sort(list);
In fact, by "sorting" the list, you will rearrange the indexes of all list elements See collections Related Javadoc on sort()
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码