The difference between Java equals method and ==

  • Data types in Java can be divided into two categories: basic data types and compound data types. The difference between the equals method and == is also different.
  1. Basic data types
    Eight data types: byte, short, char, int, long, float, double, boolean. When comparing these eight basic data types, == is often used, and the comparison is whether their values ​​are equal.

    Moreover, the equals method and == are both comparison values, and there is no difference.

  2. The composite data type is
    also the class. When two objects are compared with ==, the comparison is the storage address of the two objects in memory, unless the comparison is the same new object, and the return is true at this time, otherwise It usually returns false.

    All classes in JAVA are inherited from the base class of Object. An equals method is defined in the base class of Object. The initial behavior of this method is to compare the memory address of the object, and perform equals comparison between compound data types. , Without overriding the equals method, the comparison between them is still based on the address value of their storage location in memory

    However, this method has been overridden in some libraries, such as String, Integer, Date. In these classes, equals has its own implementation instead of the storage address of the comparison class in the heap memory.

    Therefore, in general, the equals method of Object defined by yourself is also compared with the double equal sign (==), and the result after comparison is the same as the result of ==. If you want to compare values, you need to rewrite the equals method in the class.

  • The operation of overriding the equals method in Eclipse:
    1. Double-click to enter the class that needs to override the equals method
    2. Click source -> Generate hashCode() and Equals() in the menu bar
    3. Select the element to be compared and confirmInsert picture description here
    4. In this way, when the equals method in the object created by the custom class is used, it is the value of the element in the compared object.Insert picture description here

Guess you like

Origin blog.csdn.net/cys975900334/article/details/106585823