亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Java JavaBase How to use java equals() method

How to use java equals() method

Jan 06, 2023 pm 02:42 PM
java equals()

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;

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;

(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;

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

if(!(otherObject instanceof ClassName)) return false;

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

ClassName other=(ClassName)otherObject;

(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)

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雖然對象內(nèi)的值相同,但屬于2個不同的對象,所以不相等
System.out.println(c.equals(d)); // true

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;
}

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個相同內(nèi)容的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;
  }
 }
}

Running results:

p1.equals(p2) : true
p1==p2 : false

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!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Troubleshooting Common Java `OutOfMemoryError` Scenarios Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Advanced Spring Data JPA for Java Developers Advanced Spring Data JPA for Java Developers Jul 31, 2025 am 07:54 AM

The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used

See all articles