= And equals () methods in Java
Java data types can be divided into two types:
1. The basic data type, also known as the original data type. Byte, short, char, int, long, float, double, boolean
The comparison between them applies the double equal sign (=) to compare their values.
2. Reference Data Type (class)
When they are compared with (=), they compare their storage addresses in the memory, so unless they are the same new object, their comparison result is true, otherwise the comparison result is false. All classes in Java are inherited from the base class Object. In the base class of the Object, an equals () method is defined, the initial behavior of this method is to compare the memory address of the object, but this method is overwritten in some class libraries, such as String, Integer, date has its own implementation in these classes, instead of the storage address of the comparison class in the heap memory.
For equals comparison between referenced data types, if the equals method is not overwritten, the comparison between them is based on the address value of their storage location in the memory, because the equals method of the Object is compared with the binary equal sign (=), the comparison result is the same as that of the binary equal sign (=.
Equals () method in Object
public boolean equals(Object obj) { return (this == obj); }
Example:
Person. java
package org.java.test;public class Person {private int age;private String name;public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Person(int age, String name) {this.age = age;this.name = name;}public Person() {}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + age;result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Person other = (Person) obj;if (age != other.age)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}}
MainTest. java
Package org. java. test; public class MainTest {public static void main (String [] args) {Person p1 = new Person (99, A); Person p2 = new Person (99, ); person p3 = p1; System. out. println (p1 = p2); // falseSystem. out. println (p1 = p3); // trueSystem. out. println (p1.equals (p2); // If the equals () method is not overwritten, false is returned. // After the equals () method is rewritten, the content is compared and true is returned. System. out. println (<=====================>); String s1 = hello; String s2 = hello; string s3 = new String (hello); System. out. println (s1 = s2); // trueSystem. out. println (s1 = s3); // falseSystem. out. println (s1.equals (s2); // trueSystem. out. println (s1.equals (s3); // true }}