我试图更好地理解比较器接口(interface)是如何工作的 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
最佳答案
只有一个数组,并且 words_sorted
和 words_unsorted
引用同一个数组,因为您在此处将一个引用分配给另一个引用:
String[] words_sorted = words_unsorted;
您将需要数组本身的副本,而不是数组引用的副本。使用Arrays.copyOf
通过复制旧数组来创建新数组。
String[] words_sorted = Arrays.copyOf(words_unsorted, words_unsorted.length);
关于Java:使用方法和比较器将一个数组排序到另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24174767/