【问题标题】:Java Error: Cannot convert from void to int[] [duplicate]Java 错误:无法从 void 转换为 int[] [重复]
【发布时间】:2012-11-03 04:09:25
【问题描述】:

我不明白为什么 java 认为数组“thisRow”在传递给 Arrays.sort(thisRow) 时是无效的。 “thisRow”对我来说似乎是一个 int[]。这里有什么问题?

错误消息:“类型不匹配:无法在 Test.mySort(Test.java:57) 处从 void 转换为 int[]”

private static int[][] mySort(int[][] anArray) {
    for(int i = 0; i < anArray.length; i++){
        int thisRow[] = getRow(anArray, i);
        int[] sorted = Arrays.sort(thisRow);
    }
}

//This method will get the specified row out of the array.
private static int[] getRow(int[][] anArray, int row) {
    int thisRow[] = new int[anArray[row].length];
    for(int j = 0; j < anArray[row].length; j++){
        thisRow[j] = anArray[row][j];
    }
    return thisRow;
}

【问题讨论】:

    标签: java


    【解决方案1】:

    Arrays.sort 返回 void 而不是 int[] 类型。

    根据 javadoc

    将指定的整数数组按数字升序排序。这 排序算法是一种调整过的快速排序,改编自 Jon L. Bentley 和 M. Douglas McIlroy 的“设计排序函数”, 软件实践与经验,卷。 23(11) P. 1249-1265(11 月 1993)。该算法在许多数据集上提供 n*log(n) 性能 这会导致其他快速排序降低到二次性能

    替换

    int[] sorted = Arrays.sort(thisRow);
    

    Arrays.sort(thisRow);
    

    【讨论】:

      【解决方案2】:

      Arrays.sort 对数组进行就地排序(通过改变现有对象),并且不返回任何内容。因此你应该替换

      int[] sorted = Arrays.sort(thisRow);
      

      简单

      Arrays.sort(thisRow);
      

      【讨论】:

        【解决方案3】:

        Arrays#sort 不返回 int[],它返回 void ,它对源数组本身进行排序。

        将指定的整数数组按数字升序排序。这 排序算法是一种调整过的快速排序,改编自 Jon L. Bentley 和 M. Douglas McIlroy 的“设计排序函数”, 软件实践与经验,卷。 23(11) P. 1249-1265(11 月 1993)。该算法在许多数据集上提供 n*log(n) 性能 这会导致其他快速排序降低到二次性能。

        【讨论】:

          猜你喜欢
          • 2018-02-26
          • 2012-07-21
          • 1970-01-01
          • 1970-01-01
          • 2018-08-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多