Home Java javaTutorial The difference between equals and == in java

The difference between equals and == in java

Dec 16, 2016 am 09:27 AM
equals

The difference between equals and == in ava. The value type is a stack (referred to as the stack) stored in memory, while the reference type variable only stores the address of the reference type variable in the stack, while itself is stored in the heap. The
== operation compares whether the values ​​of two variables are equal. For reference variables, it means whether the addresses stored in the heap of the two variables are the same, that is, whether the contents of the stack are the same.
Equals operation indicates whether the two variables are references to the same object, that is, whether the contents in the heap are the same.

== compares the addresses of two objects, while equals compares the contents of the two objects.
Obviously, when equals is true, == is not necessarily true;
1. equals and == in String

Java code

public class TestString {   
     public static void main(String[] args) {   
         String s1 = "Monday";   
         String s2 = "Monday";   
     }   
}
Copy after login

How many objects are there in the above program?
Let’s test it, slightly change the program

Java code

public class TestString {   
     public static void main(String[] args) {   
         String s1 = "Monday";   
         String s2 = "Monday";   
         if (s1 == s2)   
             System.out.println("s1 == s2");   
         else   
             System.out.println("s1 != s2");   
     }   
}
Copy after login

Compile and run the program, output: s1 == s2
Explanation: s1 and s2 refer to the same String object - "Monday"!

2.
If you change the program slightly, you will find something even stranger:

Java code

public class TestString {   
     public static void main(String[] args) {   
         String s1 = "Monday";   
         String s2 = new String("Monday");   
         if (s1 == s2)   
             System.out.println("s1 == s2");   
         else   
             System.out.println("s1 != s2");   
         if (s1.equals(s2))   
             System.out.println("s1 equals s2");   
         else   
             System.out.println("s1 not equals s2");   
     }   
}
Copy after login

We will create s2 using the new operator
Program output:
s1 != s2
s1 equals s2
Explanation: s1 and s2 are referenced respectively Two "Monday" String objects

3. String buffer pool

It turns out that the program will create a string buffer pool when it is running
When using an expression like s2 = "Monday" to create a string, The program will first
find objects with the same value in this String buffer pool. In the first program, s1 is
put into the pool first, so when s2 is created, the program finds s1
with the same value and will s2 refers to the object "Monday" referenced by s1
In the second program, the new operator is used. He clearly tells the program:
"I want a new one! Not the old one!" So a new "Monday" Sting Objects are created in memory. Their values ​​are the same, but their locations are different. One is swimming in the pool and the other is resting on the shore. Oops, what a waste of resources. Why do we have to separate them when they are obviously the same?
4.
Change the program again:


Java code

public class TestString {   
     public static void main(String[] args) {   
         String s1 = "Monday";   
         String s2 = new String("Monday");   
         s2 = s2.intern();   
         if (s1 == s2)   
             System.out.println("s1 == s2");   
         else   
             System.out.println("s1 != s2");   
         if (s1.equals(s2))   
             System.out.println("s1 equals s2");   
         else   
             System.out.println("s1 not equals s2");   
     }   
}
Copy after login

这次加入:s2 = s2.intern();
程序输出:
s1 == s2
s1 equals s2

原来,(java.lang.String的intern()方法
"abc".intern()方法的返回值还是字符串"abc",表面上看起来好像这个方法没什么用处。但实际上,它做了个小动作:
检查字符串池里是否存在"abc"这么一个字符串,如果存在,就返回池里的字符串;如果不存在,该方法会把"abc"添加到字符串池中,然后再返回它的引用。

更好的办法:
把所有的String都intern()到缓冲池去吧
最好在用到new的时候就进行这个操作
String s2 = new String("Monday").intern();
然后就可以用==比较两个字符串的值了


二、简单数据类型和封装类中的equals和==
Java为每一个简单数据类型提供了一个封装类,每个基本数据类型可以封装成对象类型。
除int(Integer)和char(Character),其余类型首字母大写即成封装类类型名。double (Double), float(Float),long(Long), short(Short),byte(Byte),boolean(Boolean).

以int和Integer为例说明
Java中int和Integer区别如下:
1.int是基本的数据类型,默认值可以为0;
2.Integer是int的封装类,默认值为null;
3.int和Integer都可以表示某一个数值;
4.int和Integer不能够互用,因为他们两种不同的数据类型;
int a1=1;
int a2=1;
Integer b1 =new Integer (1);
Integer b2 =new Integer (1);
------------------------------
a1==a2 这个是成立的,很简单,都知道
a1==b1 这个是不成立的.表达式的值为 false ,它们是不同的数据类型(在jdk1.5以上版本中为true)
b1==b2 这个也是不成立的.表达式的值为 false,虽然是相同的数据类型,但是它们是两个对象,==比较的是2个对象的地址,它们的地址是不相等的,内容相等都是1;
b1.equals(b2)==true 这个是成立的,表达式的值为 true. 相同数据类型,两个对象,地址不同,内容相同, quals比较的是2个对象的内容,所以成立。
(a.equals(b),因为equals比较的是两个对象,所以a,b都不能为基本数据类型,否则会出编译错误。)(在jdk1.5以上版本中,b可以为基本数据类型,a不可以)
同理,其它的封装类和基本类型也是这样的.
java中equals和==的区别
==比较的是2个对象的地址,而equals比较的是2个对象的内容。
在jdk1.5以上的版本中,基本类型和封装类能自动转化,与String类型的对象和字符串常量类似。

Java代码

Integer i1 = 123;   
       Integer i2 = 123;   
         
       int i = 123;   
         
       Integer i3 = new Integer(123);   
       Integer i4 = new Integer(123);          
                
       System.out.println("i1 == i2 = "+(i1 == i2));   
       System.out.println("i1.equals(i2) = "+(i1.equals(i2)));   
         
       System.out.println();   
       System.out.println("i3 == i4 = "+(i3 == i4));   
       System.out.println("i3.equals(i4) = "+(i3.equals(i4)));   
         
       System.out.println();   
       System.out.println("i2 == i4 = "+(i2 == i4));   
       System.out.println("i2.equals(i4) = "+(i2.equals(i4)));   
         
       System.out.println();   
       System.out.println("i == i2 = "+(i == i2));   
       System.out.println("i1.equals(i) = "+(i1.equals(i)));   
         
       System.out.println();   
       System.out.println("i == i4 = "+(i == i4));   
       System.out.println("i4.equals(i) = "+(i4.equals(i)));   
       ------------------------------   
      i1 == i2 = true   
     i1.equals(i2) = true   
     i3 == i4 = false   
     i3.equals(i4) = true   
     i2 == i4 = false   
     i2.equals(i4) = true   
     i == i2 = true   
     i1.equals(i) = true   
     i == i4 = true   
     i4.equals(i) = true
Copy after login

三、其他类怎么使用equals和==
API里的类大部分都重写了equals方法,没有重写的一般是自己写的类,
如果是你自己定义的一个类,比较自定义类用equals和==是一样的,都是比较句柄地址,
因为自定义的类是继承于object,而object中的equals就是用==来实现的,你可以看源码。

四、java里equals和hashCode之间什么关系
只是为了维护 hashCode 方法的常规协定,才要求用equals比较的两个对象的hashCode相同.
equals()和hashCode()都来自java.lang.Object.你当然可以重写.

比如a.equals(b).仅当a的内存地址相等时,才返回true.当然如String等类已经对这个方法进行了重写,比较的就不再是内存地址了.
hashCode()的值也是与内存地址相关的.所以仅当内存地址相等时,hashCode才相等.

同样很多类也重写了这个方法,还是以String为例:

Java代码

public int hashCode() {   
int h = hash;   
if (h == 0) {   
      int off = offset;   
      char val[] = value;   
      int len = count;   
  
      for (int i = 0; i < len; i++) {   
         h = 31*h + val[off++];   
      }   
      hash = h;   
   }   
   return h;   
}
Copy after login

就不在与内存地址相关了.这样做是为了保证用equals比较返回为true的两个对象,他们的hashCode是相同的. 

所以一般重写equals的时候都会重写hashCode(). 
当然,这个相当于一个约定,一个协议.你不这么做并不会错. 

五、hashCode 
在一般的应用中你不需要了解hashcode的用法,但当你用到hashmap,hashset等集合类时要注意下hashcode。 

你想通过一个object的key来拿hashmap的value,hashmap的工作方法是, 
通过你传入的object的hashcode在内存中找地址, 
当找到这个地址后再通过equals方法来比较这个地址中的内容是否和你原来放进去的一样,一样就取出value。 

所以这里要匹配2部分,hashcode和equals 
但假如说你new一个object作为key去拿value是永远得不到结果的, 
因为每次new一个object,这个object的hashcode是永远不同的,所以我们要重写hashcode, 
你可以令你的hashcode是object中的一个恒量,这样永远可以通过你的object的hashcode来找到key的地址, 
然后你要重写你的equals方法,使内存中的内容也相等。。。 




更多java中equals和==的区别相关文章请关注PHP中文网!


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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles