Collections.sort with Comparator<String[]> 编译错误

Collections.sort with Comparator<String[]> compile error

我在编译时遇到了我不明白的问题,希望得到一些帮助。 代码摘录,其他方法省略:

public class TableBuilder {
  List<String[]> rows = new LinkedList<String[]>();

  public void sortByColumn(final int colIndex) {
    int maxIdx = 0;
    for (String[] s : rows) maxIdx = Math.max(maxIdx, s.length - 1);
    if (colIndex < 0 || colIndex >= maxIdx) return

    Collections.sort(rows, new Comparator<String[]>() {
        @Override
        public int compare(String[] strings, String[] otherStrings) {
            return strings[colIndex].compareTo(otherStrings[colIndex]);
        }
    });
  }

}

我收到的错误是:

cannot return a value from method whose result type is void
                Collections.sort(rows ,new Comparator<String[]>() {
                                ^

当我将方法签名更改为 public int sortByColumn(final int colIndex) 时出现错误:

incompatible types
found   : void
required: int
                Collections.sort(rows, new Comparator<String[]>() {
                                ^

为什么此代码无法编译以及匿名 Comparator class 中的 returnsortByColumn 签名有何关系?可能是编译器错误还是我做错了什么?使用 javac 1.6.0_45.

我建议删除 return 语句,以便代码编译:

public class TableBuilder {
    List<String[]> rows = new LinkedList<String[]>();

    public void sortByColumn(final int colIndex) {
        int maxIdx = 0;
        for (String[] s : rows) maxIdx = Math.max(maxIdx, s.length - 1);
        if (colIndex < 0 || colIndex >= maxIdx) {
            Collections.sort(rows, new Comparator<String[]>() {
                @Override
                public int compare(String[] strings, String[] otherStrings) {
                    return strings[colIndex].compareTo(otherStrings[colIndex]);
                }
            });
        }
    }
}

Collections.sort 方法会将 rows 集合排序为可变对象。它不会 return 作为新对象的排序集合。

你的比较器没问题。问题是您正在尝试 return Comparator#sort 的结果,即 void。只需丢失 return 语句,您应该没问题:

if (colIndex > 0 && colIndex <= maxIdx) {
    Collections.sort(rows, new Comparator<String[]>() {
        @Override
        public int compare(String[] strings, String[] otherStrings) {
            return strings[colIndex].compareTo(otherStrings[colIndex]);
        }
    });
}

这是反斜杠突出显示的错字