需求`T仅针对某些方法扩展了Comparable <t>`</t>

时间:2012-10-27 12:26:27

标签: java generics

我正在尝试用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(...) {...}
}

3 个答案:

答案 0 :(得分:3)

您可以隐藏方法的类型TT 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的帖子)。但无论如何,其他可能的解决方案是

  1. 将需要比较的方法重构为子类
  2. 只需在相关方法中使用强制转换,这意味着只能在运行时检查该部分。

答案 2 :(得分:1)

通过常规方法,例如使用可比较的方法,这是不可能的。

如果您分享确切的要求会更好。

如果您在ArrayList / Arrays中进行排序是您的目标,那么比较不可比较的类是没用的。排序只能在相同或子类型的对象中完成。

但是如果您要使用compare来检查对象是否相等,那么我建议您重写equals(Object O)方法。