How to make user defined Class == should behave same as String ==

137 Views Asked by At

I am trying to understand internal implementation of object == operator comparison to achieve a same behavior of String == for my user defined class object.

Below is my implementation logic.

1. Bean Class

package com.study.equals;

public class SomeBean {
    int id;
    
    public SomeBean(int id) {
        this.id = id;
    }
    
    @Override
    public boolean equals(Object obj) {
        if(obj instanceof SomeBean) {
            return this.id==((SomeBean)obj).id;
        } else {
            return false;
        }
    }
    
    @Override
    public int hashCode() {
        return this.id + 2000;
    }
    
    @Override
    public String toString() {
        return "[Inside toString: " + this.hashCode() + "]";
    }
}

2. Test Class

package com.study.equals;

public class Test {

public static void main(String[] args) {
    SomeBean obj1 = new SomeBean(10);
    SomeBean obj2 = new SomeBean(10);
    if(obj1 == obj2) {
        System.out.println("true");
    }else {
        System.out.println("false");
    }   
}

}

  • Expected output: true
  • Actual output: false

Doubt

  • Can someone help me to understand why I am getting false here?
  • How can I get true as response here.
1

There are 1 best solutions below

4
On

obj1 == obj2 returns true if obj1 and obj2 are referring to exactly the same object. obj1.equals(obj2) can (as in your case) compare the contents of two objects and can return true for two different objects considered equal due to implementation of method equals.

You get the same object (same address in heap memory, same reference) by the statement obj1 = obj2.

If you do this,

obj1 = new ...
obj2 = new ...

these are always two different objects. You force java to make two new objects. These can never be the same according to ==.