【问题标题】:Organizing a List in Alphabetical order and using the append method按字母顺序组织列表并使用 append 方法
【发布时间】:2013-11-25 03:12:26
【问题描述】:
List <String> cdList = new ArrayList();
Collections.addAll(cdList, "ExampleG","ExampleB","ExampleR","ExampleX");

    bigBox.append("Original Order\n**************\n");

    for (String s : cdList)  {
    bigBox.append(s);
    bigBox.append("\n");
    }

    bigBox.append("\n\nSorted Order\n************\n");

    for (String s : cdList)  {
    bigBox.append(s);
    bigBox.append("\n");
    }

我需要按字母顺序整理List,并使其显示在“排序顺序”下方,但还需要保留原始顺序以供在原始订单行下使用。

【问题讨论】:

    标签: java list netbeans collections append


    【解决方案1】:

    原名单:

    // leave this variable untouched
    List<String> cdList = Arrays.asList("ExampleG","ExampleB","ExampleR","ExampleX");
    

    排序列表:

    List<String> sorted = new ArrayList<String>(cdList);
    Collections.sort(sorted);  // "sorted" is the sorted list
    

    现在您可以遍历cdList 和sorted,并将它们附加到bigBox:

    bigBox.append("Original Order\n**************\n");
    for (String s : cdList) {
        bigBox.append(s);
        bigBox.append("\n");
    }
    bigBox.append("\n\nSorted Order\n************\n");
    for (String s : sorted) {
        bigBox.append(s);
        bigBox.append("\n");
    }
    

    你去。

    【讨论】:

      【解决方案2】:

      你不能在同一个列表中保留(也没有必要)不同的订单。

      List <String> cdList = new ArrayList<String>();
      Collections.addAll(cdList, "ExampleG","ExampleB","ExampleR","ExampleX");
      
      
      List<String> sortedList = new ArrayList<String>(cdList);
      Collections.sort(sortedList);
      

      如果适用,我强烈建议您使用泛型。

      【讨论】:

        猜你喜欢
        • 2011-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-24
        • 1970-01-01
        • 1970-01-01
        • 2018-07-10
        • 1970-01-01
        相关资源
        最近更新 更多