How to override equals method in Java

后端 未结 9 1575
自闭症患者
自闭症患者 2020-11-22 01:41

I am trying to override equals method in Java. I have a class People which basically has 2 data fields name and age. Now I want to ove

相关标签:
9条回答
  • 2020-11-22 02:14

    I'm not sure of the details as you haven't posted the whole code, but:

    • remember to override hashCode() as well
    • the equals method should have Object, not People as its argument type. At the moment you are overloading, not overriding, the equals method, which probably isn't what you want, especially given that you check its type later.
    • you can use instanceof to check it is a People object e.g. if (!(other instanceof People)) { result = false;}
    • equals is used for all objects, but not primitives. I think you mean age is an int (primitive), in which case just use ==. Note that an Integer (with a capital 'I') is an Object which should be compared with equals.

    See What issues should be considered when overriding equals and hashCode in Java? for more details.

    0 讨论(0)
  • 2020-11-22 02:15

    Here is the solution that I recently used:

    public class Test {
        public String a;
        public long b;
        public Date c;
        public String d;
        
        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof Test)) {
                return false;
            }
            Test testOther = (Test) obj;
            return (a != null ? a.equals(testOther.a) : testOther.a == null)
                    && (b == testOther.b)
                    && (c != null ? c.equals(testOther.c) : testOther.c == null)
                    && (d != null ? d.equals(testOther.d) : testOther.d == null);
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 02:20

    Introducing a new method signature that changes the parameter types is called overloading:

    public boolean equals(People other){
    

    Here People is different than Object.

    When a method signature remains the identical to that of its superclass, it is called overriding and the @Override annotation helps distinguish the two at compile-time:

    @Override
    public boolean equals(Object other){
    

    Without seeing the actual declaration of age, it is difficult to say why the error appears.

    0 讨论(0)
提交回复
热议问题