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

后端 未结 3 1797
無奈伤痛
無奈伤痛 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:30

    Using an interface like Comparable as a method parameter doesn't make your class generic, declaring and using generic type parameters is how you make it generic.

    Quick-n-dirty answer: You are receiving the warning because you are using Comparable, which is a generic interface, as a raw type, rather than giving it a specific type arguments, like Comparable.

    To fix this, make add() generic by specifying type parameters:

    > add(T obj) { ... }
    

    But this quick fix won't fix the general problem that your class is unsafe. After all, shouldn't all the objects in your list be of the same type? This add method lets you still different types into the same list. What happens when you try to compare heterogeneous types (how do you compareTo an Object instance to an Number instance, or to a String instance)? You can depend on the user of the class to do the right thing and ensure they only stick 1 kind of thing in your list, but a generic class will let the compiler enforce this rule.

    The better approach: The proper fix is that your sorted list class should be probably be generic overall, just like the other collection classes in java.util.

    You would probably like something like:

    public class SortedList>
    implements Iterable {
        ...
        public void add(T item) { ... }
        public Iterator iterator() { ... }
        ...
    }
    

    Note that when the class is generic, the add method uses the classes formal type parameter rather than declaring its own formal type parameter.

    There should be plenty of tutorials on the web on how to create a generic class, but here's a quick example:

    http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ002

    class Pair  {  
      private X first; 
      private Y second;
      public Pair(X a1, Y a2) { 
        first  = a1; 
        second = a2; 
      } 
      public X getFirst()  { return first; } 
      public Y getSecond() { return second; } 
      public void setFirst(X arg)  { first = arg; } 
      public void setSecond(Y arg) { second = arg; } 
    }
    

提交回复
热议问题