Because each time an object is instantiated, the system allocates a memory address to the object, and the system defaults to detecting the same object based on the memory address, so it is not equal to objects instantiated in the same class.
Public class Transport { // name public String name; // type of transport Public String type; { = "vehicle"; = "Mode of transport" ; } Public void todo () { System.out.println ("vehicle can be manned");} }
View the memory address after instantiating the object and use the Equals method to determine whether it is equal:
Public Static void Main (string[] args) { new Transport (); New Transport (); // [email protected] // [email protected] // false }
The result is not equal, so the two objects are clearly the same object, how can we tell if they are the same object? Method is also very simple, we rewrite a class method to judge:
public boolean equals (Object o) { if (this = = O) return true Span style= "COLOR: #000000" >; First determine if O is this object, if it is the same object, this point to the current object if (o = = null | | GetClass ()! = O.getclass ()) return false Span style= "COLOR: #000000" >; Then determine if O is null, and whether the O class object and this class object are consistent Transport Transport = (Transport) O; Then force the O object into the Transport class object return Objects.equals (name, transport.name) && objects.equals (type, transport.type); View two objects for which the name and type property values are equal, return the result}
To run the program again:
Public Static void Main (string[] args) { new Transport (); New Transport (); // [email protected] // [email protected] // true }
Determine if two objects are equal in Java