Java “unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable”

后端 未结 3 1758
無奈伤痛
無奈伤痛 2021-02-05 04:54

I\'m trying to implement a sorted list as a simple exercise in Java. To make it generic I have an add(Comparable obj) so I can use it with any class that implements

3条回答
  •  孤街浪徒
    2021-02-05 05:13

    In essence, this warning says that Comparable object can't be compared to arbitrary objects. Comparable is a generic interface, where type parameter T specifies the type of the object this object can be compared to.

    So, in order to use Comparable correctly, you need to make your sorted list generic, to express a constraint that your list stores objects that can be compared to each other, something like this:

    public class SortedList> {
        public void add(T obj) { ... }
        ...
    }
    

提交回复
热议问题