簡體   English   中英

Java 使用方括號將 Short 轉換為 Integer

[英]Java cast Short to Integer using brackets

我有以下具有原始包裝類的代碼:

// setValue expects Integer (class)
// getValue returns Short (class)
intLength.setValue(shortLength.getValue());

Netbeans 將此標記為錯誤“類型不兼容:Short 無法轉換為整數”,並且出現編譯錯誤,這是有道理的。

但是,如果我添加一組額外的括號:

// setValue expects Integer (class)
// getValue returns Short (class)
intLength.setValue((shortLength.getValue()));

錯誤消失,代碼編譯並運行。 誰能告訴我額外的括號在做什么/為什么括號要進行鑄造。 謝謝。

正如安德烈亞斯在評論中所說的那樣; 這是一個 NetBeans 問題,NetBeans 並不總是遵循 java 規范,因為如果您檢查了Java Language Specification, Parenthesized Expressions ,它根本不會改變類型。

您可以使用 javac 和 java 命令手動檢查該代碼,並且兩次都會收到編譯錯誤。

感謝安德烈亞斯

short numShort = 15;
int numInt = (int) new Short(numShort);

或者在你的情況下

intLength.setValue( (int) new Short(shortLength.getValue()));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM