Overriding “equals” method: how to figure out the type of the parameter?

前端 未结 9 1277
栀梦
栀梦 2021-02-05 07:47

I\'m trying to override equals method for a parameterized class.

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return t         


        
9条回答
  •  不思量自难忘°
    2021-02-05 08:13

    I just ran into this problem myself, and in my -particular- case, I didn't need to know the type E.

    For example:

    public class Example {
        E value;
    
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Example other = (Example) obj;
            if (value == null) {
                if (other.value != null)
                    return false;
            } else if (!value.equals(other.value))
                return false;
            return true;
        }
    }
    

    In the above code, there is no unchecked cast because of using Example. The type parameter wildcard '?' saves the day.

提交回复
热议问题