java中==与equal()方法的区别

对于String中的“equal方法”和“==”一直有点混肴,工作的时候一直使用这个==和equal但是就是不理解,见天网上查找了一下做个笔记,记录下来让自己以后不在忘记!

先说“==”:

  “==”是用来比较两个String对象在内存中的存放地址是否相同的。例如,

1
2
3
4
5
6
7
8
9
String str0=  "test" ;
String str1=  "test" ;
 
String str2 new  String(str0);
String str3= new  String(str0);
 
 
blooean result1 = (str0==str1);//---------------true
blooean result2 = (str2==str3);//---------------false

原因:程序在运行时有一个字符串缓存机制,当String str0= "test"的时候,程序先从缓存池中查找是否有相同的String 对象,如果有的话就不会重新生成而是用缓存池中的字符串对象;如果在字符串缓存池中没找到相同的字符串对象时才会在内存中开辟一块内存区新建字符串对象。对于test1,当test1建立以后会将“test”字符串放入缓存池中,所以运行 String str1= "test"的时候就会直接从缓存池中取出相同的对象,也就说,test1和test2的内存地址是相同的,所以,result1是true。对于new来说,每new一次就会在内存中开辟一片内存区域,str2str3的内存地址是不同的,所以result2是false。

再说“equal方法”:

  equal方法是object类的方法,object类中的equal方法也使用“==”实现的,也就是说,如果直接继承object类的equal方法,则也是比较两个对象在内存中的地址是否相同,但是在String中将继承自object的equal方法覆盖啦!String中的equal方法源码如下:

复制代码
 1 /**
 2      * Compares this string to the specified object.  The result is {@code
 3      * true} if and only if the argument is not {@code null} and is a {@code
 4      * String} object that represents the same sequence of characters as this
 5      * object.
 6      *
 7      * @param  anObject
 8      *         The object to compare this {@code String} against
 9      *
10      * @return  {@code true} if the given object represents a {@code String}
11      *          equivalent to this string, {@code false} otherwise
12      *
13      * @see  #compareTo(String)
14      * @see  #equalsIgnoreCase(String)
15      */
16     public boolean equals(Object anObject) {
17         if (this == anObject) {
18             return true;
19         }
20         if (anObject instanceof String) {
21             String anotherString = (String) anObject;
22             int n = value.length;
23             if (n == anotherString.value.length) {
24                 char v1[] = value;
25                 char v2[] = anotherString.value;
26                 int i = 0;
27                 while (n-- != 0) {
28                     if (v1[i] != v2[i])
29                             return false;
30                     i++;
31                 }
32                 return true;
33             }
34         }
35         return false;
36     }
复制代码

可以看出:在String中的equal方法是比较两个String对象的内容是否相同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值