Home > Java > JavaBase > body text

How to use java equals() method

青灯夜游
Release: 2023-01-06 14:42:33
Original
9109 people have browsed it

In java, the equals() method is used to detect whether one object is equal to another object, the syntax "Object.equals(Object2)"; this method determines whether two objects have the same reference. If two Objects have the same reference, they must be equal. The equals() method cannot operate on variables of basic data types.

How to use java equals() method

The operating environment of this tutorial: windows7 system, java8 version, DELL G3 computer.

java equals() method determines whether objects are equal

The equals method is used to detect whether one object is equal to another object. Note: The equals method cannot act on variables of basic data types

In the Object class, this method determines whether two objects have the same reference. If two objects have the same reference, they must be equal.

From this point of view, it makes sense to use it as the default operation. However, for most classes, this judgment does not make sense. For example, it is completely meaningless to compare two PrintStreams in this way. However, it is often necessary to detect the equality of the states of two objects. If the states of two objects are equal, the two objects are considered equal. Therefore, equals comparison must be overridden in custom classes.

The following are suggestions for writing a perfect equals() method:

(1) The explicit parameter is named otherObject, which needs to be converted into a variable called other later

(2) Check whether this and otherObject refer to the same object:

if(this==otherObject) return true;
Copy after login

This statement is just an optimization. In fact, this is a form that is often taken. Because computing this equation is much less expensive than comparing the fields in the class one by one.

(3) Check whether otherObject is null. If it is null, return false. This test is very necessary.

if(otherObject==null) return false;
Copy after login

(4) Compare this and otherObject to see if they belong to the same class. If the semantics of equals change in each subclass, use getClass() to detect it and use it as the target class

if(getClass()!=otherObject.getClass()) return false;
Copy after login

If all subclasses have the same semantics, use instanceof to detect

if(!(otherObject instanceof ClassName)) return false;
Copy after login

(5) Convert otherObject to a variable of the corresponding type:

ClassName other=(ClassName)otherObject;
Copy after login

(6) Now start to All fields that need to be compared are compared. Use == to compare basic type fields and equals to compare object fields. If all fields match, return true, otherwise return false;

return field1==other.field1&&field2.equals(other.field2)
Copy after login

If equals is redefined in a subclass, it must include calling super.equals(other). If the test fails, equality is impossible. If the fields in the superclass are equal, the instance fields in the subclass are compared.

For array type fields, you can use the static Arrays.equals method to check whether the corresponding elements are equal.

Let’s look at a few string comparison examples:

String a = "abc";
String b = "abc";
String c = new String("abc");
String d = new String("abc");
System.out.println(a == b); // true 因为JAVA中字符串常量是共享的,只有一个拷贝
System.out.println(a == c); // false a和c属于2个不同的对象
System.out.println(a.equals(c)); // true 由于String对象的equals方法比较的是对象中的值,所以返回true。(和Object的equals方法不同)
System.out.println(c==d); // false c和d虽然对象内的值相同,但属于2个不同的对象,所以不相等
System.out.println(c.equals(d)); // true
Copy after login

How to use java equals() method

Simply put, when comparing string constants, equals returns the same result as equals. Use equals when you want to compare the values ​​of string objects.

Look at an example of using equals:

package chapter05.EqualsTest;
  
import java.util.*;
  
public class EqualsTest {
 public static void main(String[] args) {
  Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
  Employee alice2 = alice1; // reference the same object
  Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
  Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);
  
  System.out.println("alice1 == alice2: " + (alice1 == alice2));
  
  System.out.println("alice1 == alice3: " + (alice1 == alice3));
  
  System.out.println("alice1.equals(alice3): " + (alice1.equals(alice3)));
  
  System.out.println("alice1.equals(bob): " + (alice1.equals(bob)));
  
  System.out.println(bob.toString());
 }
}
  
class Employee {
 public Employee(String n, double s, int year, int month, int day) {
  name = n;
  salary = s;
  GregorianCalendar calendar = new GregorianCalendar(year, month, day);
  hireDay = calendar.getTime();
 }
  
 public String getName() {
  return name;
 }
  
 public double getSalary() {
  return salary;
 }
  
 public Date getHireDay() {
  return hireDay;
 }
  
 public void raiseSalary(double byPercent) {
  double raise = salary * byPercent / 100;
  salary += raise;
 }
  
 @Override
 public boolean equals(Object otherObject) {
  // a quick test to see if the objects are identical
  if (this == otherObject)
   return true;
  
  // must return false if the explicit parameter is null
  if (otherObject == null)
   return false;
  
  // if the classed don't match,they can't be equal
  if (getClass() != otherObject.getClass())
   return false;
  
  // now we know otherObject is a non-null Employee
  Employee other = (Employee) otherObject;
  
  // test whether the fields hava identical values
  return name.equals(other.name) && salary == other.salary
    && hireDay.equals(other.hireDay);
  
 }
  
 @Override
 public int hashCode() {
  return 7 * name.hashCode() + 11 * new Double(salary).hashCode() + 13
    * hireDay.hashCode();
 }
  
 @Override
 public String toString() {
  return getClass().getName() + "[name=" + name + ",salary=" + salary
    + ",hireDay=" + hireDay + "]";
 }
  
 private String name;
 private double salary;
 private Date hireDay;
}
  
class Manager extends Employee {
 public Manager(String n, double s, int year, int month, int day) {
  super(n, s, year, month, day);
  bouns = 0;
 }
  
 @Override
 public double getSalary() {
  double baseSalary = super.getSalary();
  return baseSalary + bouns;
 }
  
 public void setBouns(double b) {
  bouns = b;
 }
  
 @Override
 public boolean equals(Object otherObject) {
  if (!super.equals(otherObject))
   return false;
  Manager other = (Manager) otherObject;
  // super equals checked that this and other belong to the same class
  return bouns == other.bouns;
 }
  
 @Override
 public int hashCode() {
  return super.hashCode() + 17 * new Double(bouns).hashCode();
 }
  
 @Override
 public String toString() {
  return super.toString() + "[bouns=" + bouns + "]";
 }
  
 private double bouns;
}
Copy after login

What is the difference between equals() and ==?

#== : Its function is to determine whether the addresses of two objects are equal. That is, determine whether two objects are the same object.

equals(): Its function is also to determine whether two objects are equal. But it generally has two usage cases:

  • Case 1, the class does not cover the equals() method. Then comparing two objects of this class through equals() is equivalent to comparing the two objects through "==".

  • Case 2, the class overrides the equals() method. Generally, we override the equals() method to ensure that the contents of the two objects are equal; if their contents are equal, true is returned (that is, the two objects are considered equal).

Below, compare their differences through examples.

The code is as follows:

import java.util.*;
import java.lang.Comparable;
 
/**
 * @desc equals()的测试程序。
 */
public class EqualsTest3{
 
 public static void main(String[] args) {
  // 新建2个相同内容的Person对象,
  // 再用equals比较它们是否相等
  Person p1 = new Person("eee", 100);
  Person p2 = new Person("eee", 100);
  System.out.printf("p1.equals(p2) : %s\n", p1.equals(p2));
  System.out.printf("p1==p2 : %s\n", p1==p2);
 }
 
 /**
  * @desc Person类。
  */
 private static class Person {
  int age;
  String name;
 
  public Person(String name, int age) {
   this.name = name;
   this.age = age;
  }
 
  public String toString() {
   return name + " - " +age;
  }
 
  /**
   * @desc 覆盖equals方法
   */
  @Override
  public boolean equals(Object obj){
   if(obj == null){
    return false;
   }
 
   //如果是同一个对象返回true,反之返回false
   if(this == obj){
    return true;
   }
 
   //判断是否类型相同
   if(this.getClass() != obj.getClass()){
    return false;
   }
 
   Person person = (Person)obj;
   return name.equals(person.name) && age==person.age;
  }
 }
}
Copy after login

Running results:

p1.equals(p2) : true
p1==p2 : false
Copy after login

Result analysis:

In EqualsTest3.java:

  • (1) p1.equals(p2)
    This is to determine whether the contents of p1 and p2 are equal. Because Person overrides the equals() method, and this equals() is used to determine whether the contents of p1 and p2 are equal, it happens that the contents of p1 and p2 are equal; therefore, true is returned.

  • (2) p1==p2
    This is to determine whether p1 and p2 are the same object. Since they are two newly created Person objects respectively; therefore, false is returned.

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of How to use java equals() method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template