java为什么不对列表进行排序?
我可以通过实际创建一个新的ArrayList来修复它,每个元素都是一个char数组,我会认为我有每个元素的引用char数组,通过排序并将其添加到一个新列表,每个元素都将是一个排序的char数组。为了提高我对概念的理解,请解释一下。谢谢
假设我有一个单词列表,=“Stack”,“Mack”,在一个名为words的ArrayList中,我想按字母顺序对单词的每个元素进行排序,即sortedWords的元素0应该是ackSt,等等。我知道如何做到这一点,但我惊讶地发现我无法通过指向它来做到这一点
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());
}
# 1 楼答案
这里的问题是,按行排序的数组
消失了。引用未保存,因此当您调用
这是一个新阵列。你需要:
# 2 楼答案
请看一下String#toCharArray()的源代码:
每次它返回一个新的
char[]
您尚未存储返回的数组,因此排序后的排序结果已丢失