简体   繁体   中英

Collections sort generics types java

I was looking for an answer to my question for so long. I found loads of similar topics but I still do not know what to do.

I have a class where I want to store objects in sorted ArrayList.

For instance, I created this class:

public class Kwadrat implements Comparable<Kwadrat> {

    private int a;

    public Kwadrat(int a){
        this.a = a;
    }

    public int get_size(){
        return a*a;
    }

    public int compareTo(Kwadrat b){
        if(b.get_size() > get_size()){
            return -1;
        }
        if(b.get_size() < get_size()){
            return 1;
        }
        return 0;
    }
}

And here is my Sort class:

public class Sort <T> {
    ArrayList<T> arraylist;

    public Sort(){
        arraylist = new ArrayList<T>();
    }


    public void add(T element){

        arraylist.add(element);

       Collections.sort(arraylist);



    }
}

Collections.sort(arraylist); still tells me that "no instance(s) of type variable(s) T exists so that T conforms to Comparable<? super T> ".

Your Sort class currently has no bounds on its type parameter T , so it could be any type, even a type that isn't Comparable . It would accept Object , which is not Comparable . Because there is no bounds, and because the compiler sees that there are bounds on what can be passed to the single-arg Collections.sort method , there is your compiler error.

You should create the same bounds on T that Collections.sort expects.

public class Sort <T extends Comparable<T>> {

Or even better:

public class Sort <T extends Comparable<? super T>> {

Change T to T extends Comparable<T> in the public class Sort <T> { line, because the method requires <T extends Comparable<? super T>> <T extends Comparable<? super T>> parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM