public class FirstClass <E extends Comparable< E>, T extends SecondClass< E>>
如果我想声明 T 也是 Comparable 的应该怎么样才能做到啊?是不是没有可能。。。
1
kuko126 2017-08-04 10:30:20 +08:00
public class FirstClass <E extends Comparable< E>, T extends SecondClass< E>&Comparable<E>>
https://stackoverflow.com/questions/745756/java-generics-wildcarding-with-multiple-classes |
3
kuko126 2017-08-04 10:43:42 +08:00
@aznfy 那是要这样子的?
public class FirstClass<E extends Comparable<E>, T extends SecondClass<E> & Comparable<T>> { public void compare(T t1, T t2) { t1.compareTo(t2); } } |
5
momocraft 2017-08-04 10:49:10 +08:00
T 可以同时有 Comparable<T> 和 Comparable<E> 吗?不会无法重载吗?
|
6
ahill 2017-08-04 10:52:57 +08:00
SecondClass 实现 Comparable 不行吗
这样 T 不就也是实现 Comparable 的了吗 |
7
kuko126 2017-08-04 11:01:21 +08:00
@aznfy 第二个里面 T 只是 Comparable<T>的子类 如果你的 SecondClass 实现了 Comparable<E>那就不行了
下面代码可以编译通过 public class FirstClass<E extends Comparable<E>, T extends SecondClass<E> & Comparable<T>> { public void compare(T t1, T t2) { t1.compareTo(t2); } public static void main(String[] args) { FirstClass<String, ThirdClass> firstClass = new FirstClass<>(); ThirdClass t1 = new ThirdClass(1); ThirdClass t2 = new ThirdClass(2); firstClass.compare(t1, t2); } static class ThirdClass extends SecondClass<String> implements Comparable<ThirdClass> { int i; public ThirdClass(int i) { this.i = i; } @Override public int compareTo(ThirdClass o) { return 0; } } } |