简体   繁体   English

集合排序泛型类型java

[英]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. 我有一个类,我想在排序的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: 这是我的Sort类:

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> ". 仍告诉我“没有类型变量T实例存在,因此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 . 您的Sort类目前在其类型参数T上没有边界,因此它可以是任何类型,甚至是不可Comparable的类型。 It would accept Object , which is not Comparable . 它会接受Object ,它不是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. 因为没有边界,并且因为编译器发现可以传递给single-arg Collections.sort方法的边界,所以存在编译器错误。

You should create the same bounds on T that Collections.sort expects. 您应该在Collections.sort期望的T上创建相同的边界。

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改为T extends Comparable<T> public class Sort <T> { line中的T extends Comparable<T> ,因为该方法需要<T extends Comparable<? super T>> <T extends Comparable<? super T>> parameter. <T extends Comparable<? super T>>参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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