Determine if two objects are equal in Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.