使用 collections.sort() 方法对字符串进行排序
Sorting of Strings using collections.sort() method
根据 documentation:此实现将指定的列表转储到数组中,对数组进行排序,并遍历列表,从数组中的相应位置重置每个元素
鉴于下面的程序,我无法理解排序是如何在内部判断字母 'A'
小于或大于字母 'a'
的?由于这是一个字符串,字母不会被假定为 ascii 值,那么排序是如何发生的?
public class LetterASort {
public static void main(String[] args) {
ArrayList<String> strings = new ArrayList();
strings.add("aAaA");
strings.add("AaA");
strings.add("aAa");
strings.add("AAaa");
Collections.sort(strings);
for (String s : strings)
{
System.out.print(s + " "); //prints AAaa AaA aAa aAaA
}
}
}
我还尝试调试代码,这让我产生了新的疑问:数组的长度原来是 4 而不是 3,因为 collections.sort
包含在长度
中
Collections.sort
所指的"natural ordering"就是Comparable
-- which String
implements, and which defines only one method, compareTo
. So, the answer is in the definition of String.compareTo
所指的"natural ordering"。其文档说明:
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings.
词典排序基本上就是字典排序。从本质上讲,尽可能按字母顺序排列每个字母,但如果当其中一个单词用完字母时您仍然感到困惑,那么较短的单词排在第一位。
Unicode是每个字符所具有的数值。关于它有一个很好的介绍 post here(它不短,但它很好地引导您了解 unicode 是什么,以及它存在的原因)。
String
class 实现String class.
中的Comparable interface. When sort happens, compareTo(String)
method is called. For more look at the implementation of compareTo(String)
方法
根据 documentation:此实现将指定的列表转储到数组中,对数组进行排序,并遍历列表,从数组中的相应位置重置每个元素
鉴于下面的程序,我无法理解排序是如何在内部判断字母 'A'
小于或大于字母 'a'
的?由于这是一个字符串,字母不会被假定为 ascii 值,那么排序是如何发生的?
public class LetterASort {
public static void main(String[] args) {
ArrayList<String> strings = new ArrayList();
strings.add("aAaA");
strings.add("AaA");
strings.add("aAa");
strings.add("AAaa");
Collections.sort(strings);
for (String s : strings)
{
System.out.print(s + " "); //prints AAaa AaA aAa aAaA
}
}
}
我还尝试调试代码,这让我产生了新的疑问:数组的长度原来是 4 而不是 3,因为 collections.sort
包含在长度
Collections.sort
所指的"natural ordering"就是Comparable
-- which String
implements, and which defines only one method, compareTo
. So, the answer is in the definition of String.compareTo
所指的"natural ordering"。其文档说明:
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings.
词典排序基本上就是字典排序。从本质上讲,尽可能按字母顺序排列每个字母,但如果当其中一个单词用完字母时您仍然感到困惑,那么较短的单词排在第一位。
Unicode是每个字符所具有的数值。关于它有一个很好的介绍 post here(它不短,但它很好地引导您了解 unicode 是什么,以及它存在的原因)。
String
class 实现String class.
compareTo(String)
method is called. For more look at the implementation of compareTo(String)
方法