简体   繁体   English

设置vs列表java中的字母顺序

[英]Sets vs Lists Alphabetical order in java

Arent Lists a Ordered Collection, and Sets arent ordered? Arent列出有序集合,并且没有订购? 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 输出: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 输出: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: 一些例外:

  • The TreeSet is a particular Set , that keeps its elements in a naturally "sorted" order. TreeSet是一个特殊的Set ,它以自然“排序”的顺序保持其元素。
  • The LinkedHashSet is a particular Set , that does retain the insertion order. LinkedHashSet是一个特定的Set ,它确实保留了插入顺序。

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() 请参阅Collections.sort()上的相关Javadoc 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. 当你说List是有序的时,它实际上只是意味着列表保留了插入元素的顺序以及它们可以被检索的顺序是可预测的。

A Set is not ordered, its focus is just to have unique elements. Set没有订购,它的重点只是拥有独特的元素。 A TreeSet is a SortedSet which along with maintaining uniqueness, also maintains elements in a sorted order. TreeSet是一个SortedSet,它与维护唯一性一起,也按排序顺序维护元素。 And hence the result that you see above 因此,你看到上面的结果

Yes, Lists are ordered which means that the order in which items are returned by an iterator is well defined (it will return items in the order in which they were inserted). 是,列表是有序的,这意味着迭代器返回项目的顺序是明确定义的(它将按插入顺序返回项目)。 If you want the items to be returned in a different order (eg alphabetic) then you need to explicitly sort the list: 如果您希望以不同的顺序(例如字母顺序)返回项目,则需要对列表进行显式排序:

java.util.Collections.sort(myList);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM