2012-04-19 67 views
1

這是我已經取出並簡化測試的Java程序的一部分。任務是比較ArrayList中的兩個整數,並說明它們是否相等。JAVA:整數大於128時比較不起作用

下面的代碼適用於數字< 128但任何數字大於128且代碼將不起作用。

任何幫助將非常好, 謝謝。

import java.util.*; 

public class test 
{ 
public static void main (String[] args) 
{ 

Integer seat1Store = 128; 
Integer seat2Store = 128; 
Integer seat3Store = 0; 
Integer seat4Store = 0; 
Integer seat5Store = 0; 


ArrayList<Integer> proceedArray = new ArrayList<Integer>(); 


if (seat1Store !=0) 
{ 
    proceedArray.add(seat1Store); 
} 
if (seat2Store !=0) 
{ 
    proceedArray.add(seat2Store); 
} 
if (seat3Store !=0) 
{ 
    proceedArray.add(seat3Store); 
} 
if (seat4Store !=0) 
{ 
    proceedArray.add(seat4Store); 
} 
if (seat5Store !=0) 
{ 
    proceedArray.add(seat5Store); 
} 

System.out.println("ArrayList = " + proceedArray); 


boolean proceed = false; 


for(int i = 0; i<proceedArray.size();i++) 
{ 
    for(int p=0; p<proceedArray.size(); p++) 
    { 
     if(i != p) 
     { 
      if(proceedArray.get(i) == proceedArray.get(p)) 
      { 
       System.out.println("DUPLICATE"); 
       System.exit(0); 
      } 
     } 
    } 
    proceed = true; 
} 


if (proceed == true) 
{ 
    System.out.println("PROCEEDED"); 
} 




} 
} 
+0

的可能重複的[整數包裝對象僅在值127共享相同的實例?](http://stackoverflow.com/questions/5117132/integer-wrapper-objects-share-the-same-instances -only-within-the-value-127) – RanRag 2012-04-19 07:48:25

回答

6

是的,這是預期的。您不應該將對象引用與==!=進行比較。您應該使用.equals(..)代替或更好 - 使用原始文件int而不是Integer

事情是,值高達128緩存,並且JVM給你相同的對象(因此參考比較工作)。 128以上它創建一個新的實例。看看Integer.valueOf(int)的javadoc(這是幕後發生的事情)

返回一個代表指定int值的Integer實例。如果不需要新的Integer實例,則通常應優先使用此方法,而不是構造函數Integer(int),因爲此方法通過緩存經常請求的值可能會產生顯着更好的空間和時間性能。

+0

謝謝.equals()工作過。謝謝你的解釋:) – 2012-04-19 07:48:49

+0

很好的解釋。 – 2015-06-13 07:48:29

0

在比較Java中的對象時,實際上比較了使用==相等運算符時的引用而不是值。相反,您應該使用方法.equals()來比較值;

Integer a = 2423; 
Integer b = 5455; 

if (a.equals(b)) { ... 
0

您使用Integer對象而不是int primitive作爲變量類型。這隻適用於值爲128的'='運算符,因爲java將其緩存。比較對象的正確方法是.equals()函數。

但是改爲使用原始值。

int i1 = 1; 
int 12 = 2; 
List<Integer> values = ArrayList<Integer>(); 
if (!values.contains(i1)) { 
values.add(i); 
} 
if (!values.contains(i2)) { 
values.add(i2); 
}