比较 Java 中的泛型
Comparing Generics in Java
如果我有一个使用模板 <T>
的 class,我该如何比较两个类型 T 的变量?我的一位朋友告诉我,您应该将 <T extends Comparable<? super T>>
添加到 class 以比较类型 T 变量,但我不太理解他的意思。这是我的 class:
public class SomeClass<T extends Comparable<? super T>>
{
public SomeClass(){}
public T foo(T par, T value)
{
if(value > par)
{
return value
}
else
{
return par;
}
}
}
在我的 Main.java 中:
SomeClass<Integer> sc = new SomeClass<Integer>();
Integer val1 = 10;
Integer val2 = 5;
System.out.println(sc.foo(val1, val2));
我得到的错误是:
error: bad operand types for binary operator '>' if(value > par)
>
运算符只能用于基元,不能用于对象。您需要使用 compareTo
方法来比较对象。
您的 T
实现了 Comparable
, so you should use its compareTo()
方法。
if (value.compareTo(par) > 0) {
....
}
此外,请注意在 java 中它被称为 Generics,而不是 Templates,这与 C++ 有很大不同模板(比 C++ 版本弱得多,也简单得多)。一个重要的区别是它不适用于基元,仅适用于对象——所以如果你想使用 SomeClass<int>
——那是不可能的。 (但是您可以使用 SomeClass<Integer>
)。
另请注意,您不能分配
T = 0;
因为 T
是一个对象。
如果我有一个使用模板 <T>
的 class,我该如何比较两个类型 T 的变量?我的一位朋友告诉我,您应该将 <T extends Comparable<? super T>>
添加到 class 以比较类型 T 变量,但我不太理解他的意思。这是我的 class:
public class SomeClass<T extends Comparable<? super T>>
{
public SomeClass(){}
public T foo(T par, T value)
{
if(value > par)
{
return value
}
else
{
return par;
}
}
}
在我的 Main.java 中:
SomeClass<Integer> sc = new SomeClass<Integer>();
Integer val1 = 10;
Integer val2 = 5;
System.out.println(sc.foo(val1, val2));
我得到的错误是:
error: bad operand types for binary operator '>' if(value > par)
>
运算符只能用于基元,不能用于对象。您需要使用 compareTo
方法来比较对象。
您的 T
实现了 Comparable
, so you should use its compareTo()
方法。
if (value.compareTo(par) > 0) {
....
}
此外,请注意在 java 中它被称为 Generics,而不是 Templates,这与 C++ 有很大不同模板(比 C++ 版本弱得多,也简单得多)。一个重要的区别是它不适用于基元,仅适用于对象——所以如果你想使用 SomeClass<int>
——那是不可能的。 (但是您可以使用 SomeClass<Integer>
)。
另请注意,您不能分配
T = 0;
因为 T
是一个对象。