我正在尝试用Java编写泛型类。该类中的一些方法需要T extends Comparable<T>
。我怎样才能使T
只有在使用其中一种方法时才需要具有可比性?或者也许还有其他方法可以组织我的课程?
这是我正在尝试实施的课程。我打算在可比较和不可比较的类型上使用它和数组。
// I know Java has its own containers, but this
// is homework and I'm not allowed to use them
class Array<T>
{
// Some methods that pose no
// special restrictions on T
// These require that T be comparable
public Array<T> union(...) {...}
public Array<T> intersect(...) {...}
}
答案 0 :(得分:3)
您可以隐藏方法的类型T
。 T
Test
与此T
的{{1}}不同。
CompareMethod
现在的例子
public static class Test<T> {
<T extends Comparable<T>> void compareMethod(T t, Class<T> classt) {
}
void normalMethod(T t) {
}
}
<强>更新强>
在被诅咒这个解决方案后,我在java API中进行了一些搜索,并且 Test<String> test = new Test<String>();//Comparable class
test.compareMethod("",String.class);//works fine
Test<Random> tes1t = new Test<Random>();//Non Comparable class
tes1t.compareMethod(new Random(),Random.class);//Compilation error here
tes1t.normalMethod(new Random());//Works fine
new Test<Random>().compareMethod("",String.class);// Not a good but can be valid
new Test<String>().compareMethod(new Random(),Random.class);//Compilation error here
方法
toArray()
答案 1 :(得分:2)
编辑:看起来这毕竟是可能的(参见AmitD的帖子)。但无论如何,其他可能的解决方案是
答案 2 :(得分:1)
通过常规方法,例如使用可比较的方法,这是不可能的。
如果您分享确切的要求会更好。
如果您在ArrayList / Arrays中进行排序是您的目标,那么比较不可比较的类是没用的。排序只能在相同或子类型的对象中完成。
但是如果您要使用compare来检查对象是否相等,那么我建议您重写equals(Object O)方法。