How to override equals method in Java

后端 未结 9 1570
自闭症患者
自闭症患者 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: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);
        }
    
    }
    

提交回复
热议问题