欢迎访问宙启技术站
智能推送

equals()函数的用法

发布时间:2023-06-23 12:41:36

The equals() function in Java is used to compare two objects for equality. It is a method of the Object class and is used to compare two objects for value equality. This method is mainly used to compare the contents of two objects to see if they are equal or not.

Java’s equals() function is often used in conjunction with hashCode() function, which is also implemented in the Object class. Together, these two functions are used to compare the equality of objects in Java.

The basic syntax of the equals() method in Java is as follows:

public boolean equals(Object obj)

The equals() method is a function that is implemented in the Object class and takes in an object as its parameter. It returns a boolean value, which indicates whether the two objects compared are equal or not.

The equals() method can be used for all Java objects, as all Java objects are derived from the Object class. However, it is mandatory to implement this method in custom classes if you want to compare objects of that class.

When comparing two objects using Java’s equals() function, the following things are checked:

1. Reference equality: This means that the two objects being compared are the same object or not.

2. Value equality: This means that the two objects being compared have the same value or not.

The difference between these two concepts is important. Reference equality is based on whether two objects are the same object. This means that if two objects have the same reference (i.e., they are the same object), they are considered equal. On the other hand, value equality is based on whether two objects have the same value.

If two objects are compared for reference equality, the equals() function returns true only if the two objects are the same object. However, if two objects are compared for value equality, the equals() function returns true only if the values of the two objects are the same.

Here is an example of how to use the equals() function in Java:

public class TestEquals {

public static void main(String[] args) {

String str1 = "Hello World";

String str2 = new String("Hello World");

System.out.println(str1.equals(str2)); // Returns true

}

}

In this example, str1 and str2 represent two different objects with the same value. The equals() function compares these two objects for value equality and returns true, since both objects have the same value.

In summary, Java’s equals() function is used to compare two objects for value equality. It is implemented in the Object class and can be used to compare any Java objects. When comparing two objects, the equals() function checks both reference and value equality. If two objects have the same reference or the same value, the equals() function returns true.