2011-06-01 44 views
1

我的問題是如果實習生正在使用字符串和字符串有一個 SPC(字符串池常量)它和實習生的概念也使用整數, 所以有沒有任何整數池常量?它的工作如何?關於java中的實習生

class InternExample 
{ 
public void print() 
{  
Integer i=10; 
Integer j=10; 
String c="a"; 
    String s="a"; 
System.out.println(i==j);// prints true 
System.out.println(c==s);//prints true 
} 
public static void main(String args[]) 
{ 
    new InternExample().print(); 
} 
} 
+0

閱讀本http://www.devx.com/tips/Tip/42276整數 – PeterMmm 2011-06-01 09:50:29

+0

鬆散的聯繫:這裏是一個討厭的攻擊在Java中自動裝箱的,研究它可以幫助你理解的自動裝箱更好:http://thedailywtf.com/Articles/Disgruntled-Bomb-Java-Edition.aspx – Bolo 2011-06-01 10:19:39

回答

5

自動裝箱使用共同的值的高速緩存,如在§ 5.1.7 Boxing Conversion of the JLS定義:

如果被裝箱值ptruefalse,一個byte,在範圍內的char\u0000\u007f ,或或short數字在-128和127之間,那麼讓r1r2是任何兩個裝箱轉換的結果p。它始終是這種情況,r1 == r2

注意,這不是 「實習」,但是。該術語僅用於對String文字所做的操作以及可以使用String.intern()明確執行的操作。

7

加入@Joachim Sauer's答案,我們可以變化的上界高速緩存值

一些選項是

  1. -Djava.lang.Integer.IntegerCache.high =值
  2. -XX:AutoBoxCacheMax =值
  3. -XX:+ AggressiveOpts

鏈接Java Specialist

4

請注意您的「平等假設」。例如,對於整數:

Integer a = 69; 
    Integer b = 69; 
    System.out.println(a == b); // prints true 
    Integer c = 1000; 
    Integer d = 1000; 
    System.out.println(c == d); // prints false 

這是由於內部實現整數的,具有預先存在的對象爲整數爲小的值(從-127到128我覺得)。但是,對於更大的整數,每次都會創建一個不同的對象Integer。

對於你的字符串也是一樣的,你的源代碼中的字符串都將被編譯器鏈接到同一個對象......他足夠聰明。但是,當您從文件中讀取字符串或在運行時創建/操作某個字符串時,它們將不再相同。

String a = "x"; 
    String b = "x"; 
    String c = new String("x"); 
    System.out.println(a == b); // prints true 
    System.out.println(a == c); // prints false