英文:
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<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);
}
}
Output:
[ 2, 0, 1, 3, 4, 5, 6, 7, 8, 9]
Thanks!
答案1
得分: 5
注意字符串" 2"
中有一个空格字符。这意味着在进行字符串比较时,由于空格的ASCII码低于任何其他数字的ASCII码," 2"
会比所有其他字符串都小,这就是为什么它排在前面。去除该空格字符将导致字符串按(词典顺序)排序。
英文:
Notice that there's a space character in the string " 2"
. 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, " 2"
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
从数组中删除包含 " 2"
的空格。这会影响你的排序结果。
英文:
Get rid of the space in the array where you have " 2"
. 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论