0

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
1
  • 1
    You don't have two arrays. You have two references to the same array. In addition, Arrays.sort() acts on the array you pass in; you can't pass in one array to Arrays.sort() and get a different array out. Commented Jun 12, 2014 at 0:31

2 Answers 2

5

There is only one array, and words_sorted and words_unsorted are referring to the same array because you assigned one reference to another here:

String[] words_sorted = words_unsorted;

You will need a copy of the array itself, not a copy of the reference to the array. Use Arrays.copyOf to create a new array by copying the old array.

String[] words_sorted = Arrays.copyOf(words_unsorted, words_unsorted.length);
Sign up to request clarification or add additional context in comments.

Comments

0

String[] words_sorted = words_unsorted; is simply making words_sorted point to the same memory location as words_unsorted, meaning that any changes you make to either will be reflected in the other

Instead, you can copy the array using something like...

System.arraycopy(words_unsorted, 0, words_sorted, 0, words_unsorted.length);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.