2015-05-28 46 views
0

這將是一個簡單的問題(或者至少我認爲)。我必須將一個Long對象與一個長基元進行比較。兩個多頭之間的比較不能按預期工作

我的代碼簡化:

long primitiveLong = 285825645621; 
Long objectLong = new Long(285825645621); 

if(primitiveLong == objectLong.longValue()){ 
    System.out.print("They are equals"); 
} 

我預計它會工作,但事與願違,有人可以解釋我爲什麼?

在此先感謝。

編輯

好吧,我用明確的數字做了一個錯誤,我把我在這裏的代碼:

long identifier = mMarkers.get(marker); 
long currentId = item.getId().longValue(); 

if (currentId==identifier) 
    System.out.print("They are equals"); 

在調試

enter image description here

編輯2

這是一個在調試模式下的IDE(Android Studio)的bug,我試過在另一個IDE上,它使用相同的代碼很好。所以感謝大家的答案,但問題是另一個,我不能指望。

+0

如果該代碼已進入if循環或無或者我們應該猜測一下你認爲應該發生的事情:) – CKing

+0

@ChetanKinger代碼應該在if語句中輸入 –

+0

它不會編譯,對於編譯在數字的末尾添加L,那麼這個代碼應該工作原因是@ChetanKinger'if'不是一個循環,而是一個聲明;) –

回答

0

首先這必須應該給你編譯錯誤,因爲編譯器想起285825645621作爲一個整數,但它比INT更大,所以你需要改變你的代碼是這樣的:

long primitiveLong = 285825645621l; //add and l at the end of your number so compiler know that it is a long not an int 
Long objectLong = new Long(285825645621l); //do the same thing here 

if(primitiveLong == objectLong.longValue()){ 
    System.out.print("They are equals"); 
} 

,這將打印:They are equals

+0

正如我所說這是我的代碼更簡化的版本。我沒有明確的數字,但返回它們的方法 –

+0

@Fondesa,所以你不會簡化你的代碼!請提供更多信息以及您提供的數據,但我無法解釋爲什麼發生這種情況。 – Lrrr

+0

查看對我的問題的編輯! –

0

您可以使用文字值還是該限制285825645

If you are using beyond the limit you will get compile error 

long primitiveLong = c; 
      Long objectLong = new Long(285825645); 

      if(primitiveLong == objectLong.longValue()){ 
       System.out.print("They are equals"); 
      }