[英](Novice) Java generics: Comparable
I have a class called Generic
.我有一个名为
Generic
。 I am assigned to create a boolean method called matches()
that receives another Generic
as a parameter and returns true if the two stored values can be found in the current Generic
.我被分配创建一个名为
matches()
的布尔方法,该方法接收另一个Generic
作为参数,如果可以在当前Generic
找到两个存储的值,则返回 true。 Order of the values is not important.值的顺序并不重要。
public class Generic<T extends Comparable<? super T>> {
...
public boolean matches(Class Generic){
return this.valueA = that.valueA && this.valueB = that.valueB): }
...
}
I am scrabbling to figure out how the class is able to store multiple values for valueA
and valueB
and distinguish this.valueA
from the other one.我正在努力弄清楚该类如何能够为
valueA
和valueB
存储多个值并将this.valueA
与另一个值区分开来。 Should I refer to the concept called reflection for more info?我应该参考称为反射的概念以获取更多信息吗?
If the purpose of type parameter T
is for fields valueA
and valueB
to be of that type, and that matches()
should use the fact that they are Comparable
(since T extends Comparable
), this is how:如果类型参数
T
的目的是使字段valueA
和valueB
属于该类型,并且matches()
应该使用它们是Comparable
的事实(因为T extends Comparable
),则方法如下:
public class Generic<T extends Comparable<? super T>> {
private T valueA;
private T valueB;
public boolean matches(Generic<T> that){
return (this.valueA.compareTo(that.valueA) == 0 &&
this.valueB.compareTo(that.valueB) == 0);
}
}
Of course, assuming that the referenced type enforces that Comparable
is consistent with equals , then you don't really need Comparable
at all:当然,假设引用的类型强制
Comparable
与 equals 一致,那么您根本不需要Comparable
:
public class Generic<T> {
private T valueA;
private T valueB;
public boolean matches(Generic<T> that){
return (this.valueA.equals(that.valueA) &&
this.valueB.equals(that.valueB));
}
}
Be aware that neither of these two examples can handle null values for valueA
and valueB
.请注意,这两个示例都不能处理
valueA
和valueB
空值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.