java不兼容类型编译器错误

Rod*_*vid 1 java

我是Java新手,这段代码在编译时给我错误:

import java.util.*;

public class Sorts {


    public List<Integer> ascendent(List<Integer> list) {
          return Collections.sort(list);
        }
    public List<Integer> descendant(List<Integer> list) {
          return Collections.sort(list, Collections.reverseOrder());
    }  

    public static void main(String[] args) {

        Sorts sorts = new Sorts(); 

        List<Integer> list = new ArrayList<Integer>();
        list.addAll(Arrays.asList(1,9,2,8,3,7,4,6,5,5));

        System.out.println(sorts.ascendent(list).toString());    
    }

}
Run Code Online (Sandbox Code Playgroud)

错误是从ascendent和descendent方法返回的行:


需要不兼容的类型:java.util.List(java.lang.Integer)
found:void

但在我看来,我正在正确地投射我的ListArray对象,出了什么问题?

Bac*_*ash 7

Collections.sort是的void,你不能在return声明中使用它.

此外,Collections.sort修改原始列表,因此您根本不必返回新列表.

删除return:

public void ascendent(List<Integer> list) {
      Collections.sort(list);
}
public void descendant(List<Integer> list) {
      Collections.sort(list, Collections.reverseOrder());
}  
Run Code Online (Sandbox Code Playgroud)

另外,相应地更改您的代码.这个:

System.out.println(sorts.ascendent(list).toString()); 
Run Code Online (Sandbox Code Playgroud)

必须更改为:

sorts.ascendent(list);
System.out.println(list); 
Run Code Online (Sandbox Code Playgroud)

  • 将签名更改为"public void" (3认同)