I am having trouble figuring out how to write my equals method using generics as I am sure if using instanceOf is necessary. Im trying to compare that two ItemPairs are the same (logically equivalent) if both items within the pair are the same (logically equivalent)
Here is my attempt at it:
public class ItemPair<T> {
private T item1;
private T item2;
public ItemPair(T item1, T item2) {
this.item1 = item1;
this.item2 = item2;
}
public T getItem1() {
return item1;
}
public void setItem1(T item1) {
this.item1 = item1;
}
public T getItem2() {
return item2;
}
public void setItem2(T item2) {
this.item2 = item2;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof T) {
return this.item1.equals(this.item2);
} else {
return false;
}
}
}
equals()should be comparingthistoobj, which is usually anotherItemPair, notitem1toitem2.if (! getClass().isInstance(obj)) {return false;} ItemPair<T> other = getClass().cast(obj);.