【问题标题】:Comparator for Generic Interface Without Warnings没有警告的通用接口比较器
【发布时间】:2010-10-29 17:22:33
【问题描述】:

给定:

public interface PrimaryKey<Key extends Comparable> {
    Key getKey();
}

public class PrimaryKeyComparator implements Comparator<PrimaryKey> {
    public int compare(PrimaryKey first, PrimaryKey second) {
        return first.getKey().compareTo(second.getKey());
    }
}

这种组合有效,但会发出有关原始类型的警告。我尝试了各种添加类型参数的方法,但我尝试的每种组合都会破坏代码。

【问题讨论】:

  • 使用KeyTKey 作为通用占位符是一种非常容易混淆阅读您代码的人的方法。 Java 使用 ETKV 作为占位符名称是有原因的。
  • 完全同意 R. Bemrose 的观点。 Key 看起来像一个类或接口的名称。

标签: java generics comparator


【解决方案1】:

试试这个:

public interface PrimaryKey<TKey extends Comparable<TKey>> {
    TKey getId();
}

public class PrimaryKeyComparator<TKey extends Comparable<TKey>> 
                                 implements Comparator<PrimaryKey<TKey>> {
    public int compare(PrimaryKey<TKey> first, PrimaryKey<TKey> second) {
        return first.getId().compareTo(second.getId());
    }
}

【讨论】:

  • 通用参数TKey 应该是&lt;K extends Comparable&lt;? super K&gt;&gt;,它允许使用实现原始Comparable 而不是Comparable&lt;T&gt; 的类,或Comparable&lt;T&gt; 类的子类。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多