java determines whether two objects are the same object instance code

  • 2020-05-26 08:34:45
  • OfStack

java determines whether two objects are the same object

Compare the referenced address with "==" and the value with equals. So we have new and we have the same object and we have the same properties, and we have different properties when we compile, because we're calling the superclass which is the equals method of Object, and we're going to have to override this equals method.


public class Test5 {

  public static void main(String[] args) {

    User mUser1 = new User("zhangsan", "123456");
    User mUser = new User("zhangsan", "123456");
    System.out.println(mUser == mUser1);
    System.out.println(mUser.equals(mUser1));

  }
}

class User {
  String name = "";
  String pwd = "";



  @Override// Overrides the parent class equals methods 
  public boolean equals(Object obj) {
    if (obj instanceof User) {
      User mUser = (User) obj;
      if (mUser.name.equals(name)&&mUser.pwd.equals(pwd)) {
        return true;
      }
    }
    return super.equals(obj);
  }


  public User(String name, String pwd) {
    super();
    this.name = name;
    this.pwd = pwd;
  }

}

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: