【发布时间】:2014-08-02 05:02:00
【问题描述】:
我试图更好地理解比较器接口 在 Java 中与对象和类交互。
我有一个未排序单词的字符串数组。 我想将该数组复制到第二个数组 并按字母顺序仅第二个数组。
当我调用 Array.sort 方法时 并传入第二个数组和比较器对象作为参数, 两个数组最终按字母顺序排序 我不明白为什么????
这是一个例子:
import java.util.Arrays;
import java.util.Comparator;
public class test2 {
public static void main(String[] args) {
// first array is unsorted
String[] words_unsorted = { "the", "color", "blue", "is", "the",
"color", "of", "the", "sky" };
// copy array to another array to be sorted
String[] words_sorted = words_unsorted;
// instantiate a reference to a new Comparator object
Comparator<String> listComparator = new Comparator<String>() {
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}
};
// invoke sort method on words_sorted array
Arrays.sort(words_sorted, listComparator);
// compare arrays /
int size = words_sorted.length;
for(int i = 0; i < size; i++) {
System.out.println(words_unsorted[i] + " " + words_sorted[i]);
}
}
}
输出:
blue blue
color color
color color
is is
of of
sky sky
the the
the the
the the
【问题讨论】:
-
你没有两个数组。您对 same 数组有两个 references。另外
Arrays.sort()作用于你传入的数组;你不能将一个数组传递给Arrays.sort()并得到另一个数组。
标签: java arrays string sorting comparator