2014-02-13 90 views
1

在一個方法中,我記得有一個錯誤在具有以下代碼的行引發。ClassCastException和不兼容

java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Integer 

Integer count = (Integer) result[1]; 

,我取代了代碼

Integer count = ((BigDecimal) result[1]).intValue(); 

錯誤已經一去不復返了。

但是,一些如何我在新項目中得到了相同的代碼片段的以下錯誤。

java.lang.ClassCastException: java.math.BigDecimal incompatible with java.lang.Integer 

只是想知道,這兩者是相同或不相同。

+0

這是很難幫助你不知道result'是什麼'... –

+4

如果你得到了相同的代碼片斷相同的錯誤,往往不是,這是同樣的問題,同樣的解決方案將適用。 – SudoRahul

+0

結果數組的類型是什麼? – Sanjeev

回答

0

兩者都不相同 Integer count = (Integer) result[1];試圖將BigDecimal對象轉換爲整數。總是會引發異常。

Integer count = ((BigDecimal) result[1]).intValue();如果您的結果有BigDecimal對象,這將工作。

更好地檢查你是否正確編譯了你的代碼。

0

BigDecimal.intValueExact()(或BigDecimal.intValue()):

Converts this BigDecimal to an int. This conversion is analogous to a narrowing primitive conversion from double to short as defined in the Java Language Specification: any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this BigDecimal value as well as return a result with the opposite sign.

Plase考慮到BigDecimal的可能含有值大於Integer.MAX_VALUE。

參考:here