下面是一个示例代码:
public class Example> {
public void compareValues(T value1, T value2) {
if (value1.compareTo(value2) > 0) {
System.out.println("value1 is greater than value2");
} else if (value1.compareTo(value2) < 0) {
System.out.println("value1 is less than value2");
} else {
System.out.println("value1 is equal to value2");
}
}
public static void main(String[] args) {
Example example = new Example<>();
example.compareValues(5, 10); // value1 is less than value2
Example example2 = new Example<>();
example2.compareValues("apple", "banana"); // value1 is less than value2
}
}
在上面的示例中,我们创建了一个泛型类Example
,并将泛型类型T
限定为实现了Comparable
接口的类型。然后,我们编写了一个名为compareValues
的方法,该方法接受两个参数,这两个参数必须是实现了Comparable
接口的类型。
在compareValues
方法中,我们使用compareTo
方法比较了两个值value1
和value2
。根据比较结果,我们输出不同的消息。在main
方法中,我们创建了Example
类的实例,并调用compareValues
方法进行比较不同类型的值。