最近筆者遇到一個問題
Integer cameraType=1
if (cameraType.intValue() == SourceTypeEnum.ANFANG.getType(){ }
枚舉值是1
發現不同類型的兩這種寫法居然成立,且結果為true
於是查了很多資料 ,發現官方API 有這種說法:
If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands
解釋:
如果相等運算符的操作數都是數值類型,或者其中一個是數值類型,另一個可轉換為數值類型(§5.1.8),則對操作數執行二進制數值提升
這句話很明顯解釋了現象 首先兩都是數值類型,比較的時候 通過對他們進行各自的二進制轉化 來進行比較 因為兩者值是一樣的 所以提升后 結果一樣