Java determines whether two objects are the same object
The referenced address is compared with "==", and the value is compared with equals. Then, the properties of the two identical objects in new are the same, and why they are not the same when compiling? This is because we call the equals method of the parent class, which is the Object. Here we need to rewrite 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//Rewrite the equals method of the parent class 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 it can help you. Thank you for your support for this site!