简体   繁体   English

修改方法,使参数可以是实现Comparable的任何类型

[英]Modifying a method so the arguments can be any type that implements Comparable

I would like to modify the following method so its arguments can be of any type that implements the Comparable interface. 我想修改以下方法,以便它的参数可以是实现Comparable接口的任何类型。 The method's return type should be the same as the type of its parameter variables. 方法的返回类型应与其参数变量的类型相同。

public static int max(int a, int b) {   
    if (a >b) 
        return a;  
    else 
        return b;
}

So in modifying it, I could just use <T extends Comparable<T>> , but how would I go about making the return types the same? 所以在修改它时,我可以使用<T extends Comparable<T>> ,但是我如何才能使返回类型相同呢?

You essentially want something like this: 你基本上想要这样的东西:

public static <T extends Comparable<T>> T max(T a, T b) {
    int n = a.compareTo(b);
    if (n > 0)
        return a;
    if (n < 0)
        return b;
    return a;
}

You can of course simplify this to the following (thank you to @pickypg for the notice): 您当然可以将此简化为以下内容(感谢@pickypg的通知):

public static <T extends Comparable<T>> T max(T a, T b) {
    return a.compareTo(b) < 1 ? b : a;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实现可比较接口的类型的 LinkedList - LinkedList of type that implements the comparable interface 错误:选择类型中的方法排序(Comparable [])不适用于参数(int []) - Error: the method sort (Comparable []) in the type Selection is not applicable for the arguments (int[]) 公开课 <Generic type> 实现可比 - Public class <Generic type> implements Comparable 实现与方法比较的Comparable接口的小部件类 - Widget class that implements the Comparable interface that compares to method Java泛型-类型T中的方法validate(T,T)不适用于自变量(可比较,可比较 <capture#11-of ?> ) - java generics - The method evaluate(T,T) in the type T is not applicable for the arguments (Comparable, Comparable<capture#11-of ?>) Java泛型:Comparable类型的compareTo(capture#2-of?扩展E)方法不适用于自变量(Comparable) - Java Generics :The method compareTo(capture#2-of ? extends E) in the type Comparable is not applicable for the arguments (Comparable) 我可以用吗 <T implements Comparable> 要不就 <Comparable> - Can I use <T implements Comparable> or just <Comparable> Java中的泛型方法应该具有什么签名,以便它可以接受任何<T实现Iteralbe并存储List <U >>和......? - What signature should a generic method in Java have so that It can accept any <T that implements Iteralbe and stores List<U>> and…? 未定义 Comparable 类型的 compareTo(Comparable) 方法 - The method compareTo(Comparable) is undefined for the type Comparable 在方法调用期间修改参数时是否有任何保证? - Are there any guarantees when modifying arguments during method invocation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM