Home  >  Article  >  Technology peripherals  >  The difference and usage of equals() and == in Java

The difference and usage of equals() and == in Java

WBOY
WBOYforward
2024-03-07 15:28:11335browse

In Java development, there is a seemingly simple topic, but there are a lot of topics and questions on the Internet, which is what is the difference between equals() and the == operator

  • ==: The operator is used to compare whether the addresses of two objects are equal.
  • equals(): The method is used to compare whether the contents of two objects are equal.

Today Content introduction, takes about 9 minutes

The difference and usage of equals() and == in JavaPicture

To better understand the difference, let’s look at an example:

String str1 = new String("Hello");String str2 = new String("Hello");System.out.println(str1.equals(str2)); // 输出 trueSystem.out.println(str1 == str2); // 输出 false

In the example, although the contents of the two strings are the same, their addresses in memory are different. Therefore, using the .equals() method to compare their contents will return true, while using the "==" operator to compare their addresses will return false

1. Overriding the .equals() method

Those who have studied the basics of Java should know that all Java classes inherit the Object class by default. There is an .equals() method in the Object class

public boolean equals(Object obj) {return (this == obj);}

You can find .equals( from the code ) method uses the == operator for comparison by default. If the subclass does not override the equals() method, then use the == operator and the equals() method. The result is exactly the same - used to compare whether the memory addresses of two objects are equal.

But the actual situation is that many classes override the equals() method. This is because the memory address comparison requirements are strict and do not meet the needs of all real-life scenarios. For example, the String class, when comparing, most I just want to determine whether the contents are equal, and I don't really want to know whether the memory address is equal (whether it is an object).

In the article on in-depth study of the Java string constant pool, we have learned that the Java virtual machine allocates a separate space for strings in order to optimize memory utilization and improve performance - the string constant pool.

It is recommended to use String s = "Hello" to create a string object instead of using the new keyword, because new requires additional allocation of memory space on the heap.

1.1. The equals() method of the String class

The equals() method of the String class of Jdk11

public boolean equals(Object anObject) { //如果是同一个对象(即两个引用指向内存中的同一块地址),则直接返回trueif (this == anObject) {return true;} //如果是String类型的实例if (anObject instanceof String) { //Object类型的对象强制转换为String类型String aString = (String)anObject;//如果当前字符串对象和传入的字符串对象的编码方式相同if (coder() == aString.coder()) { //如果当前字符串和传入的字符串都是Latin1编码,则调用StringLatin1类的equals方法进行比较;如果其中一个或两个字符串是UTF16编码,则调用StringUTF16类的equals方法进行比较return isLatin1() ? StringLatin1.equals(value, aString.value): StringUTF16.equals(value, aString.value);}}return false;}

Special note: Latin1 (also known as (ISO 8859-1) and UTF-16 (Unicode conversion format 16-bit) are two different character encoding methods

Although Latin1 and UTF-16 are two encoding methods, the difference is not big, just take Look at the equals() method from UTF-16

@HotSpotIntrinsicCandidatepublic static boolean equals(byte[] value, byte[] other) {if (value.length == other.length) {int len = value.length >> 1;for (int i = 0; i 

Note: The source code of the equals() method of Java8 and Java11 is different. The equals() method of JDK8

public boolean equals(Object anObject) {// 如果是同一个对象(即两个引用指向内存中的同一块地址),则直接返回trueif (this == anObject) {return true;}// 如果是String类型的实例if (anObject instanceof String) {////Object类型的对象强制转换为String类型String anotherString = (String)anObject;int n = value.length;// 如果字符串长度相等if (n == anotherString.value.length) {char v1[] = value;char v2[] = anotherString.value;int i = 0;// 判断每个字符是否相等while (n-- != 0) {if (v1[i] != v2[i])return false;i++;}return true;}}return false;}

1.2. Example explanation

Example 1:

new String("hello").equals("hello")

What is the output result?

equals of String class The method compares whether the contents of the string objects are equal. Because they are all "Hello", the result is true

Example 2:

new String("hello") == "hello";

What is the output result?

== Whether the object addresses compared by the operator are equal, == The left side is the object created in the heap, and the right side is the string constant pool object. Although the contents are equal, the addresses are not equal, so the result is false

Example 3:

new String("hello") == new String("hello");

What is the output result?

The object coming out of new must be a completely different memory address, so the result is false

Example 4:

"hello" == "h"+"ello"

What is the output result?

h and ello are both in the string constant pool, so the compiler will It is automatically optimized to hello, so the result is true

Example 5:

new String("hello").intern() == "hello"

What is the output result?

new String("hello") During execution, the object will be created first in the string constant pool, and then in the heap; when executing the intern() method, it is found that the object 'hello' already exists in the string constant pool, so it returns directly The object in the string constant pool is referenced, and then compared with 'hello' in the string constant pool, so the result is true

In-depth analysis of String.intern() has already introduced the reasons

2. Other comparison methods

In addition to the .equals() method and the "==" operator, there are some other comparison methods that can be used:

  • 1.Objects.equals() method: This static method can be used to compare whether two objects are equal. There is no need to determine whether the object is empty before calling.
Objects.equals("Hello", new String("Hello")); // 返回 true
  • 2. The .contentEquals() method of the String class: This method can be used to compare a string with any character sequence (such as StringBuffer, StringBuilder, String, CharSequence) are equal.
String str = "Hello";StringBuffer buffer = new StringBuffer("Hello");System.out.println(str.contentEquals(buffer)); // 输出 true

The above is the detailed content of The difference and usage of equals() and == in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete