没有警告的通用接口比较器

发布于 2024-09-30 00:11:44 字数 417 浏览 0 评论 0原文

鉴于:

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());
    }
}

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

Given:

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

and

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

This combination works, but gives warnings about raw types. I've tried various ways of adding the type arguments, but every combination I've tried breaks the code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忆依然 2024-10-07 00:11:44

试试这个:

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());
    }
}

Try this:

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());
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文