简体   繁体   English

为什么不对列表进行排序?

[英]Why does this not sort the list?

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. 我可以通过实际上创建一个新的ArrayList来修复它,每个元素都是一个char数组,我以为我拥有每个元素char数组的引用,并对其进行排序并将其添加到新列表中,每个元素都是一个排序的char数组。 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. 假设我有一个单词列表,即“ Stack”,“ Mack”,在名为单词的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());
              }

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() : 请看一下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[] . 每当它返回一个新的char[]

You haven't stored the returned array hence the sorting result has been lost after sorting. 您尚未存储返回的数组,因此排序后的排序结果已丢失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM