【问题标题】:Why does Collections.sort not put these strings in the right order? [closed]为什么 Collections.sort 没有按正确的顺序排列这些字符串? [关闭]
【发布时间】:2021-01-05 15:29:11
【问题描述】:

我是 Java 初学者。我不明白为什么这段代码不能正常工作。我糊涂了。有人可以解释为什么。这是我的代码:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class HW20 {

    public static ArrayList<String> abc(String ... strings) {

        ArrayList<String> strings1 = new ArrayList<>(Arrays.asList(strings));
        Collections.sort(strings1);
        return strings1;
    }

    public static void main(String[] args) {

        ArrayList<String> strings1 = abc("1", "9", "4", " 2", "6", "8", "3", "5", "7", "0");
        System.out.println(strings1);
    }
}

输出:

[ 2, 0, 1, 3, 4, 5, 6, 7, 8, 9]

谢谢!

【问题讨论】:

  • 您到底想完成什么?你也可以做 import java.util.*;而不是三个导入语句。我假设您想要输出 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]?

标签: java sorting collections


【解决方案1】:

请注意,字符串" 2" 中有一个空格字符。这意味着在比较字符串时,由于空格的 ASCII 代码低于任何其他数字的 ASCII 代码," 2" 将比较少于所有其他字符串,这就是为什么它首先出现。删除该空格字符将导致字符串以(按字典顺序)排序。

【讨论】:

    【解决方案2】:

    去掉数组中" 2" 所在的空间。它让你不满意。

    【讨论】:

      【解决方案3】:

      我假设您想按 asc 对字符串进行排序 你应该改变

      Collections.sort(strings1); -> Collections.sort(strings1, Collator.getInstance());

      所以Colletions utils可以理解

      【讨论】:

      • 这有必要吗?这不是默认行为吗?
      • @templatetypedef 请注意" 2",有1个空格
      • 不,默认行为是字典顺序。就像任何其他语言一样,正如您所期望的那样。这将在其他类似字符之前放置一个空格。尝试订购字符串时,您会在其他任何地方看到相同的情况。例如尝试用空格命名 windows 文件,让资源管理器按名称对它们进行排序,同样的行为。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多