开发者

how to specify "type" for generics when invoking their methods

The problem i'm having is that javac thinks T doesnt implement compareTo(). So how can i do this while still staying "generic". Wouldnt casting to specific type defeat the purpose of using generic type?

public class Tree<T> implements Comparable<T> {

    private T value;


    public T getValue() {
        return value;
    }

    @Override
    public int compareTo(T arg0) {
        // TODO Auto-generated method stub
        if (this.getValue() != null) {
    开发者_如何学编程        return this.getValue().compareTo(arg0);        // compilation problem
        }
    }
}


You need to refine the generic type argument to Tree<T extends Comparable<T>> -- otherwise the compiler has no idea that your T object has a compareTo(T t) method defined for it.


The signature for a generic compareTo should be (T arg0), not a plain Objct.


Use the interface for value

e.g.

public class Tree<T> implements Comparable<T> {



private Comparable<T> value;


  @Override
  public int compareTo(T o) {
    // TODO Auto-generated method stub
        if (value != null) {
            return value.compareTo(o);  
        }
        return 0;
  }


}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜