这里的参数并不限定,这就需要写一个通用的比较方法,因此需要用到泛型。
代码如下:
public class TestMaxParam {
public static <T extends Comparable<T>> T maxParam(T x, T y, T z) {
T max = x;
if (y.compareTo(max) > 0) {
max = y;
}
if (z.compareTo(max) > 0 ) {
max = z;
}
return max;
}
public static void main(String[] args) {
System.out.println("1.1, 2,3, 4.5, max=" + maxParam(1.1, 2.3, 4.5));
System.out.println("6, 3, 1, max=" + maxParam(6, 3, 1));
System.out.println("apple, ox, orange, max=" + maxParam("apple", "ox", "orange"));
}
}结果:
1.1, 2,3, 4.5, max=4.5
6, 3, 1, max=6
apple, ox, orange, max=ox
本文介绍了一个使用Java泛型实现的求三个参数中最大值的方法。该方法能够接受不同类型但实现了Comparable接口的对象,如Double、Integer和String,并返回这三个对象中的最大值。

被折叠的 条评论
为什么被折叠?



