I have a class called 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
. 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. 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:
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:
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.