2014-01-17 138 views
1

我有一個問題,當我比較folderInfoData.getFolderInfoRecord().getInfoCode()map.get("infoCode")下面的代碼。兩個都給value=2但我的問題是,它沒有輸入if條件。在java中比較int值?

這裏的例子:

if (folderInfoData.getFolderInfoRecord().getInfoCode().equals(map.get("infoCode"))) { 
     showNotification(pageResourceBundle.getText("MSG_SAME_INFO_ALREADY_EXISTS")); 
      return; 
    } 

之前,我用Google搜索它不適合我有效:Comparing Integer objects vs int

誰能告訴mehow可以解決這個問題?

感謝

+0

什麼是'getInfoCode()的返回類型' – Abubakkar

+0

它返回整數 – Sitansu

+0

@Sitansu'Integer'或'int'?事實證明,這可以有所作爲。 –

回答

3

在評論中您聲明map宣佈爲Map<String, Object>。這可能是問題所在。

當您撥打map.get("infoCode")時,您將收回Object

如果:

  • Object實際上是Integer
  • folderInfoData.getFolderInfoRecord().getInfoCode()一個實例返回一個Integer
  • Integer小號包含相同的值

那麼這樣的:

if (folderInfoData.getFolderInfoRecord().getInfoCode() 
     .equals(map.get("infoCode"))) { 

評價爲true

所以要麼他們是兩個Integers但不包含相同的值,或他們是不同類型的對象和不是相等。 (或者,「infoCode」不會在地圖上存在,它的返回null

1

你必須檢查兩者是否具有正確的值,因此整數的情況下,即通過平等的測試。當兩個整數值相同時,測試肯定會通過。請調試您的代碼並找出答案。將其更改爲==沒有用處。

+0

我的信息代碼超過1000的情況下,它不工作 – Sitansu

+0

爲什麼.equals不工作和==工作?你應該解釋一下,因爲默認的.equals實現了一個引用(==)比較。你打算說.equals()覆蓋getInfoCode()返回的對象中的實現是錯誤的嗎? – Scorpion

+1

如果正在編譯,這是不正確的。 Map不能返回一個原語,因此除了引起一些不需要的拆箱之外,它不會有任何區別。 –

0

如果返回字符串

if (Integer.parseInt(folderInfoData.getFolderInfoRecord().getInfoCode()) == Integer.parseInt(map.get("infoCode"))) { 
     showNotification(pageResourceBundle.getText("MSG_SAME_INFO_ALREADY_EXISTS")); 
      return; 
    } 

其他

if (folderInfoData.getFolderInfoRecord().getInfoCode() == map.get("infoCode")) { 
     showNotification(pageResourceBundle.getText("MSG_SAME_INFO_ALREADY_EXISTS")); 
      return; 
    } 

嘗試,這也是

if (folderInfoData.getFolderInfoRecord().getInfoCode().toString.trim().equals(map.get("infoCode").toString().trim())) { 
     showNotification(pageResourceBundle.getText("MSG_SAME_INFO_ALREADY_EXISTS")); 
      return; 
    } 
+0

Integer類型的parseInt(String)方法不適用於參數(Object) – Sitansu

2

如果你想使用.equals(),最好的辦法是確保它總是返回Integer而不是int

int num1 = Integer.parseInt(folderInfoData.getFolderInfoRecord().getInfoCode()); 
int num2 = Integer.parseInt(map.get("infoCode")); 

if (new Integer(num1).equals(new Integer(num2))) { 
    showNotification(pageResourceBundle.getText("MSG_SAME_INFO_ALREADY_EXISTS")); 
     return; 
} 
+0

Integer num2 = new Integer(map.get(「infoCode」));構造函數Integer(Object)未定義 – Sitansu

+1

@Sitansu if你得到_構造函數Integer(Object)是undefined_這意味着'map.get(「infoCode」)'value已經是'Integer'類型 – DnR

+0

@DnR不,這意味着他的'Map'被聲明爲'Map '(見評論)。對於'Integer',沒有構造函數(或'parseInt())',它需要一個'Object' –

-1

似乎你在比較int和Integer。 Java將一個整數轉換成一個int自動

所以

int a = 2; 
Integer b = a; 
System.out.println(a == b); 

成爲

int a = 2; 
Integer b = new Integer(a); 
System.out.println(a == b.valueOf()); 

所以,如果你想使用等號,見拉法埃爾答案。否則你可以使用==