2014-04-01 47 views
-7

等於VS ==和Java 7:等於在Java 6在Java 6和Java不同的作品7

傢伙不幸的是我沒有一個例子,因爲我在學校幫助一些學生和他們的某個時候在使用此結構java 7,甚至可以使用一些對象,我只是想知道java 6和7之間是否存在差異,並且我知道當我們使用字符串時我們應該使用平等。

我測試過字符串和對象與等於,但我意識到,有時候沒有問題使用==而不是等於在Java 7中,是否有任何差異的方式Java 6和7處理?

+7

請顯示一個簡短但完整的程序來展示問題。沒有細節,這個問題太模糊,無法回答。 –

+0

我有點懷疑有一個巨大的差異。 –

+2

你不應該使用「==」作爲字符串內容相等的比較。 –

回答

5

我敢肯定你比較字符串和字符串常量,一般

Object o = new Object(); 
Object o2 = new Object(); 
o == o2 -> False as it compares object identity 
o.equals(o2) -> False because default implementation of equals compares identities. 


String a = new String("a1"); 
String b = new String ("a1"); 
String c = "a1"; 
String d = "a1"; 

a == b -> False as it compares object identity 
a.equals(b) -> True as String ovverrides the method and it compares String's content 
c == d -> True because these are declared as string literals and have the same identity (interned Strings are stored in memory only once to reduce memory usage) 
c.equals(d) -> True because content of strings is the same. 
1

有許多地方==可能奏效的情況下。例如,某些Integer和String值共享一個通用緩存,並且如果您比較的值全部來自該緩存,則會得到一個匹配結果。

例如:

Integer.valueOf(1) == Integer.valueOf(1) 

是事實,但

new Integer(1) == new Integer(1) 

是假的。

一般情況下,除非在非常受控制的情況下,您不應該將==用於比較,否則不值得冒險。