java中“==”和equal區別


8個月以后就要正式找工作啦,我覺得現在是時候花時間好好深入研究一下以前比較混餚的知識。這就當作是自我成長的第一步!

對於String中的“equal方法”和“==”一直有點混餚,今天重新看了一下他們兩點的區別,記錄下來讓自己以后不在忘記!

先說“==”:

  “==”是用來比較兩個String對象在內存中的存放地址是否相同的。例如,

String test1 = "test";
String test2 = "test";

String test3 = new String(test2);
String test4  =new String(test2);


blooean result1 = (test1==test2);
blooean result2 = (test3==test4);

其中:result1為true,result2為false。

原因:程序在運行時有一個字符串緩存機制,當String test1 = "test"的時候,程序先從緩存池中查找是否有相同的String 對象,如果有的話就不會重新生成而是用緩存池中的字符串對象;如果在字符串緩存池中沒找到相同的字符串對象時才會在內存中開辟一塊內存區新建字符串對象。對於test1,當test1建立以后會將“test”字符串放入緩存池中,所以運行 String test2 = "test"的時候就會直接從緩存池中取出相同的對象,也就說,test1和test2的內存地址是相同的,所以,result1是true。對於new來說,每new一次就會在內存中開辟一片內存區域,test3和test4的內存地址是不同的,所以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對象的內容是否相同。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM