7
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

4 回答 4

7

Collections.sort期望 aList而不是Collection,所以改变你的sortPrint方法 From

Collection<Integer>ints

List<Integer> ints

题外话:

而不是直接在具体的类程序上工作到一个接口

更喜欢

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

超过

ArrayList<Integer> ints = new ArrayList<Integer>();
于 2012-05-25T04:44:35.077 回答
2

这样做怎么样:

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

Collections.sort()只为List

于 2012-05-25T04:44:35.387 回答
0

为您的进口

import java.util.*;

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

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 中)你不能有两次相同的元素

于 2012-05-25T04:48:16.277 回答
0

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

java.until.Collections文档:这里

这个类只支持Collections.sort(list)and Collections.sort(list,comparator) ,所以不能排序Collection。试试List

于 2012-05-25T04:48:29.613 回答