Is "instanceOf" used when using generics?

It’s hard for me to figure out how to write my equals method using generics, as I am sure that if you use instanceOf, you need to. Im trying to compare that two ItemPairs are the same (logically equivalent) if both elements inside the pair are the same (logically equivalent)

Here is my attempt:

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;
    }
}

}
+4
source share
1 answer

Your method equalsshould not determine if the first element matches the second element of the same object ItemPair. He must determine whether the two are ItemPairequal to each other:

public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (!(obj instanceof ItemPair))
        return false;
    IterPair other = (IterPair) obj;
    return this.item1.equals(other.item1) && this.item2.equals(other.item2);
}

For cases where any of the elements is null, additional conditions may be required.

+5
source

Source: https://habr.com/ru/post/1676051/


All Articles