I was able to fix it by actually creating a new ArrayList, with each element being a char array, by I would've thought I had the reference of each elements char array, and by sorting it and adding it to a new list, that each element would be a sorted char array. Just to improve my conceptual understanding, please shed some light. Thanks
Suppose I have aa list of words, = "Stack", "Mack", in an ArrayList named words, I want to sort each element of words alphabetically, ie element 0 of sortedWords should be ackSt, etc. I know how to do this, but I was surprised as to how I couldn't do it by pointing to it.
ArrayList<ArrayList<String>> groupedAnagrams = new ArrayList<>();
ArrayList<char[]> sortedWords = new ArrayList<>();
for(String word : words){
//char[] sortedWord = word.toCharArray();
Arrays.sort(word.toCharArray());
sortedWords.add(word.toCharArray());
}
The issue here is that the array that gets sorted in the line
Arrays.sort(word.toCharArray());
disappears. The reference isn't saved, so when you call
sortedWords.add(word.toCharArray());
this is a new array. You need:
char[] sortedWord = word.toCharArray();
Arrays.sort(sortedWord);
sortedWords.add(sortedWord);
Please have a look at source code of String#toCharArray() :
/**
* Converts this string to a new character array.
*
* @return a newly allocated character array whose length is the length
* of this string and whose contents are initialized to contain
* the character sequence represented by this string.
*/
public char[] toCharArray() {
char result[] = new char[count];
getChars(0, count, result, 0);
return result;
}
Every time it returns you a new char[]
.
You haven't stored the returned array hence the sorting result has been lost after sorting.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.