为什么 Collections.sort 没有将这些字符串排序正确?

huangapple go评论68阅读模式
英文:

Why does Collections.sort not put these strings in the right order?

问题

我是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]

谢谢
英文:

I'm a beginner in Java. I don't understand why this code does not work properly. I'm confused. Can someone please explain why. Here's my code:

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

public class HW20 {

    public static ArrayList&lt;String&gt; abc(String ... strings) {

        ArrayList&lt;String&gt; strings1 = new ArrayList&lt;&gt;(Arrays.asList(strings));
        Collections.sort(strings1);
        return strings1;
    }

    public static void main(String[] args) {

        ArrayList&lt;String&gt; strings1 = abc(&quot;1&quot;, &quot;9&quot;, &quot;4&quot;, &quot; 2&quot;, &quot;6&quot;, &quot;8&quot;, &quot;3&quot;, &quot;5&quot;, &quot;7&quot;, &quot;0&quot;);
        System.out.println(strings1);
    }
}

Output:

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

Thanks!

答案1

得分: 5

注意字符串&quot; 2&quot;中有一个空格字符。这意味着在进行字符串比较时,由于空格的ASCII码低于任何其他数字的ASCII码,&quot; 2&quot;会比所有其他字符串都小,这就是为什么它排在前面。去除该空格字符将导致字符串按(词典顺序)排序。

英文:

Notice that there's a space character in the string &quot; 2&quot;. This means that when the strings are being compared, since the ASCII code for a space is lower than the ASCII code for any other numbers, &quot; 2&quot; will compare less than all the other strings, which is why it comes first. Removing that space character will cause the strings to come back in (lexicographically) sorted order.

答案2

得分: 1

从数组中删除包含 &quot; 2&quot; 的空格。这会影响你的排序结果。

英文:

Get rid of the space in the array where you have &quot; 2&quot;. It is throwing off your sort.

答案3

得分: 1

我假设您想要按升序对字符串顺序进行排序
您应该更改

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

这样,集合工具就能理解了。

英文:

I assume that you wanna sort string order by asc
You should change

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

So Colletions utils can understand

huangapple
  • 本文由 发表于 2020年9月19日 01:07:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63960028.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定