如何编写方法签名“T实现Comparable< T>”在Java? [英] How to write a method signature "T that implements Comparable<T>" in Java?

查看:232
本文介绍了如何编写方法签名“T实现Comparable< T>”在Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的插入 -method应该有什么签名?我正在努力与泛型。在某种程度上,我想要 Comparable< T> T ,我试过 <可比< T>扩展T>

What signature should I have on my insert-method? I'm struggling with the generics. In a way, I want both Comparable<T> and T and I have tried with <Comparable<T> extends T>.

public class Node<T> {

    private Comparable<T> value;

    public Node(Comparable<T> val) {
        this.value = val;
    }

    // WRONG signature - compareTo need an argument of type T
    public void insert(Comparable<T> val) {
        if(value.compareTo(val) > 0) {
            new Node<T>(val);
        }
    }

    public static void main(String[] args) {
        Integer i4 = new Integer(4);
        Integer i7 = new Integer(7);

        Node<Integer> n4 = new Node<>(i4);
        n4.insert(i7);
    }
}


推荐答案

不确定你想要实现的目标,但是你不应该在类的声明中包含它吗?

Not sure what you are trying to achieve, but should you not include that in the declaration of the class?

public static class Node<T extends Comparable<T>> { //HERE

    private T value;

    public Node(T val) {
        this.value = val;
    }

    public void insert(T val) {
        if (value.compareTo(val) > 0) {
            new Node<T>(val);
        }
    }
}

注意:这是一个好习惯使用< T extends Comparable<?超级T>> 而不是< T extends Comparable< T>>

Note: it is good practice to use <T extends Comparable<? super T>> instead of <T extends Comparable<T>>

这篇关于如何编写方法签名“T实现Comparable&lt; T&gt;”在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆