比较的是两个字符串时,如果字符串相同则返回0;如果按照字典排序,第一个字符串比第二个字符串靠前,就返回负值。
public class Test {
public static <T extends Comparable<T>> T maximum(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.printf("%s, %s 和 %s 中最大的数为 %s\n", "pear",
"apple", "orange", maximum("pear", "apple", "orange"));
}
}
输出:pear, apple 和 orange 中最大的数为 pear