没有合适的排序错误方法

时间:2012-05-25 04:38:33

标签: java

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Collection;

public class ClearlyAnArrayList
{
    public static void main(String[] args){
        Scanner kb=new Scanner(System.in);
        ArrayList<Integer>ints=new ArrayList<Integer>();
        int num=kb.nextInt();
            while(num!=-1){
            ints.add(num);
            }
    sortPrint(ints);
}

    public static void sortPrint(Collection<Integer>ints){
        Collections.sort(ints);
        for(Integer i:ints){
        System.out.printf("%d\n",i);
        }
}
}
  

这是我用blueJ编译的代码。当我编译它时,我得到了一个   从“no suitable method for sort(java.util.Collection<java.lang.Integer>)”开始然后继续的冗长错误   说更多我不理解的东西。

对此的解决方案是我使用的List不是集合而Collections.sort()需要List

  

对于所有人来说,还有比单数import语句更好的方法   我的工具?

给出的解决方案是

import java.util.*;

4 个答案:

答案 0 :(得分:6)

Collections.sort需要List而不是Collection,因此请更改sortPrint方法 来自

Collection<Integer>ints

List<Integer> ints

Offtopic:

而不是直接处理具体类program to an interface

体型

List<Integer> ints = new ArrayList<Integer>();

ArrayList<Integer> ints = new ArrayList<Integer>();

答案 1 :(得分:2)

这样做:

public static void sortPrint(List<Integer> ints){
    Collections.sort(ints);
    for(Integer i:ints){
    System.out.printf("%d\n",i);
    }

Collections.sort()仅适用于List

答案 2 :(得分:0)

供您导入

import java.util.*;

sort方法对List进行排序,而不是集合,因此请将声明更改为:

public static void sortPrint(List<Integer> ints)

您还可以拥有一个在插入过程中自行排序的集合,您的程序将成为:

public static void main(String[] args){
        Scanner kb=new Scanner(System.in);
        TreeSet<Integer>ints=new TreeSet<Integer>();
        int num=kb.nextInt();
        while(num!=-1){
            ints.add(num);
        }
        //already sorted
    }

警告,在Set(以及TreeSet中)中,您不能拥有相同的元素两次

答案 3 :(得分:0)

阅读文档(或尝试按Ctrl + Space获取信息)。

java.until.Collections文档:here

此课程仅支持Collections.sort(list)Collections.sort(list,comparator) ,因此您无法对Collection进行排序。请尝试使用List

相关问题