Implementing Comparable with a generic class

て烟熏妆下的殇ゞ 提交于 2019-11-30 04:59:57

Item (without any type argument) is a raw type, so:

  1. We could pass any kind of Item to Item.compareTo. For example, this would compile:

    new Item<String>().compareTo(new Item<Integer>())
    
  2. The method o.getT() returns Comparable instead of T, which causes the compilation error.

    In the example under the 1st point, after passing Item<Integer> to Item.compareTo, we would then erroneously pass an Integer to String.compareTo. The compilation error prevents us from writing the code which does that.

I think you just need to remove the raw types:

public class Item<T extends Comparable<T>>
implements Comparable<Item<T>> {

    ...

    @Override
    public int compareTo(Item<T> o) {
        return getT().compareTo(o.getT());
    }
}

You're using raw types in your class definition (Item<T> is generic, but you're omitting the type parameter <T>), change it to:

class Item<T extends Comparable<T>> implements Comparable<Item<T>>

(Note the last <T>)

The compareTo method will then have to be changed as well:

public int compareTo(Item<T> o) { // again, use generics
    return getT().compareTo(o.getT());
}

I think, this makes more sense. I have compiled and tested the following :

class Item<E extends Comparable<E>> implements Comparable<E> {

 private int s;
 private E t;

 public E getE() {
     return t;
 }

 @Override
 public int compareTo(E e) {
     return getE().compareTo(e);
 }

 public int compareTo(Item<E> other)
    {
        return getE().compareTo(other.getE());
    }

 }

Notice that you now need to have two compareTo methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!