我有一个String叫做的数组myArray(为了争论,我们只是说它包含了一个故事中的单词).我想将此数组传递给一个方法,该方法将按字母顺序对它们进行排序并分析单词.我在SO上看了这个,许多人建议使用这个场景java.util.Arrays.sort(myArray).所以我在我的方法中使用了这一行,传入了myArray它,并对它进行了计算等.
但是,最近我注意到这将永久排序.myArray.也就是说,在我退出方法之后,数组仍然会被排序.有没有办法让我只在方法范围内对数组进行排序?
示例代码:
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
}
Run Code Online (Sandbox Code Playgroud)
String temp[] = java.util.Arrays.copyOf(doc1,doc1.length);
java.util.Arrays.sort(temp);
Run Code Online (Sandbox Code Playgroud)