簡體   English   中英

為什么不對列表進行排序?

[英]Why does this not sort the list?

我可以通過實際上創建一個新的ArrayList來修復它,每個元素都是一個char數組,我以為我擁有每個元素char數組的引用,並對其進行排序並將其添加到新列表中,每個元素都是一個排序的char數組。 為了增進我的概念理解,請闡明一下。 謝謝

假設我有一個單詞列表,即“ 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());
              }

這里的問題是在行中排序的數組

Arrays.sort(word.toCharArray());

消失。 該參考未保存,因此在您致電時

sortedWords.add(word.toCharArray());

這是一個新數組。 你需要:

char[] sortedWord = word.toCharArray();
Arrays.sort(sortedWord);
sortedWords.add(sortedWord);

請看一下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;
}

每當它返回一個新的char[]

您尚未存儲返回的數組,因此排序后的排序結果已丟失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM