0

I have an String array called myArray (for the sake of argument, let's just say it contains words from a story). I want to pass this array to a method that will sort them alphabetically and analyze the words. I've looked this up on SO and many people have suggested for this scenario to use java.util.Arrays.sort(myArray). So I used this line in my method, passed in myArray, and performed calculations on it, etc etc.

However, it recently came to my attention that this will permanently sort myArray. That is, the array will still be sorted after I come out of the method. Is there a way for me to only sort the array within the scope of the method?

Example code:

public static double uniqueWords(String[] doc1) {

    java.util.Arrays.sort(doc1)

    ... // count up the number of unique words in this array

    return COUNT_OF_UNIQUE_WORDS;
}

public static void main(String[] args) {
    String[] document;
    ... // put values in the array
    System.out.println(uniqueWords(document));
    System.out.println(java.util.Arrays.toString(document));   // here the array will still be sorted, which I DON'T want
}

3 Answers 3

8
String temp[] = java.util.Arrays.copyOf(doc1,doc1.length);
java.util.Arrays.sort(temp);
Sign up to request clarification or add additional context in comments.

Comments

4

Make a copy of the array, sort that copy and use the same.

  String [] sortedDocuments = new Sting[document.length];
  Systems.arraycopy(document, 0, sortedDocuments , 0, document.length);
  Arrays.sort(sortedDocuments );

or

  String [] sortedDocuments = Arrays.copyOf(document, document.length);
  Arrays.sort(sortedDocuments );

Use the sortedDocuments array with-in your method. Your original array document is left untouched.

Comments

1

If all you want to do is to count unique words, better use the following code. There's no need to sort your array to count unique elements.

public int countUniqueElements(Object[] array) {
    return new HashSet(Arrays.asList(array)).size();
}

1 Comment

yeah I knew that. I actually do more things that find unique words, I just wanted something simple to type so I wouldn't have to include ALL of my code haha. It was the first thing to come to mind. But thanks!

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.