有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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());
              }

共 (2) 个答案

  1. # 1 楼答案

    这里的问题是,按行排序的数组

    Arrays.sort(word.toCharArray());
    

    消失了。引用未保存,因此当您调用

    sortedWords.add(word.toCharArray());
    

    这是一个新阵列。你需要:

    char[] sortedWord = word.toCharArray();
    Arrays.sort(sortedWord);
    sortedWords.add(sortedWord);
    
  2. # 2 楼答案

    请看一下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[]

    您尚未存储返回的数组,因此排序后的排序结果已丢失