Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

no suitable method for sort error

Tags:

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);
        }
}
}

This is the code I'm compiling with blueJ When I compile it I get a lengthy error which starts off "no suitable method for sort(java.util.Collection<java.lang.Integer>)" and then goes on to say more stuff I don't understand.

The solution to this was that I was using a List which is not a collection and Collections.sort() expects a List

Also is there a better way than singular import statements for all my utils?

The solution given was

import java.util.*;
like image 222
Matthew Optional Meehan Avatar asked May 25 '12 04:05

Matthew Optional Meehan


2 Answers

Collections.sort expects a List and not Collection, so change your sortPrint method From

Collection<Integer>ints

To

List<Integer> ints

Offtopic:

Instead of working directly on concrete classes program to an interface.

Prefer

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

Over

ArrayList<Integer> ints = new ArrayList<Integer>();
like image 129
mprabhat Avatar answered Sep 29 '22 01:09

mprabhat


what about just doing this:

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

Collections.sort() is only for List

like image 22
Shawn Avatar answered Sep 29 '22 01:09

Shawn