I'm trying to better understand how the Comparator Interface in Java interacts with objects and classes.
I have a string array of unsorted words. I'd like to copy that array to a second array and alphabetize only the second array.
When I invoke the Array.sort method and pass in the second array and the comparator object as arguments, both arrays end up being sorted alphabetically and I do not understand why????
Here is an example:
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]);
}
}
}
Output:
blue blue
color color
color color
is is
of of
sky sky
the the
the the
the the
Arrays.sort()acts on the array you pass in; you can't pass in one array toArrays.sort()and get a different array out.