Best practices regarding equals: to overload or not to overload?

后端 未结 8 962
刺人心
刺人心 2020-12-09 02:48

Consider the following snippet:

import java.util.*;
public class EqualsOverload {
    public static void main(String[] args) {
        class Thing {
                 


        
8条回答
  •  独厮守ぢ
    2020-12-09 02:54

    As this question is 10 years old and the original author is probably not interested in the answer anymore, I'll add some information that can be useful to developers looking for an answer nowadays.

    For Android developers, Android Studio contains a template that will pop-up when trying to overload the equal operator. It also generates a proper hashCode method, and the resulting overridden equals method would look like this:

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Thing thing = (Thing) o;
        return x.equals(thing.x);
    }
    

提交回复
热议问题