我有两个类,一个在<T extends Comparable<T>
类标题中包含 itemslf class MaximumTest2 <T extends Comparable<T>>
,另一个在其中包含public class MaximumTest
但方法扩展了 Comparable,如下面的代码所示。
实现方式有什么不同,一种比另一种更好。顺便说一句,上面两个类做同样事情的方式。
class MaximumTest2 <T extends Comparable<T>> { // determines the largest of three Comparable objects public T maximum(T x, T y, T z) // cant make it static but why?? { T max = x; // assume x is initially the largest if ( y.compareTo( max ) > 0 ){ max = y; // y is the largest so far } if ( z.compareTo( max ) > 0 ){ max = z; // z is the largest now } return max; // returns the largest object } } public class MaximumTest { // determines the largest of three Comparable objects public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; // assume x is initially the largest if ( y.compareTo( max ) > 0 ){ max = y; // y is the largest so far } if ( z.compareTo( max ) > 0 ){ max = z; // z is the largest now } return max; // returns the largest object } public static void main( String args[] ) { MaximumTest2 test2 = new MaximumTest2(); System.out.println(test2.maximum(9, 11, 5)); System.out.printf( "Max of %d, %d and %d is %d\n\n", 3, 4, 5, maximum( 3, 4, 5 ) ); System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) ); System.out.printf( "Max of %s, %s and %s is %s\n","pear", "apple", "orange", maximum( "pear", "apple", "orange" ) ); }
}
- 当我尝试使方法
public T maximum(T x, T y, T z)
静态时,我在 Eclispe 中收到以下错误:cannot make a static reference to a non-static type T
. 我不明白这是什么意思?我不能让它静态吗?
- 当我尝试使方法
最后,短语究竟是什么意思
<T extends Comparable<T>
?