简体   繁体   English

Java 使用方括号将 Short 转换为 Integer

[英]Java cast Short to Integer using brackets

I have the following code that has primitive wrapper classes:我有以下具有原始包装类的代码:

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

Netbeans flags this as an error "incompatible types: Short cannot be converted to Integer", and I get a compile error, which makes sense. Netbeans 将此标记为错误“类型不兼容:Short 无法转换为整数”,并且出现编译错误,这是有道理的。

However if I add an extra set of brackets:但是,如果我添加一组额外的括号:

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

The error disappears and the code compiles and works.错误消失,代码编译并运行。 Can anyone tell me what the extra brackets are doing/why do the brackets do the casting.谁能告诉我额外的括号在做什么/为什么括号要进行铸造。 Thanks.谢谢。

So as Andreas told in the comments;正如安德烈亚斯在评论中所说的那样; It's a NetBeans problem, NetBeans doesn't always follow the java specs, because if you checked the Java Language Specificate, Parenthesized Expressions , it doesn't change the type at all.这是一个 NetBeans 问题,NetBeans 并不总是遵循 java 规范,因为如果您检查了Java Language Specification, Parenthesized Expressions ,它根本不会改变类型。

You can check that code manually, using javac and java commands and you'll receive a compilation error the both times.您可以使用 javac 和 java 命令手动检查该代码,并且两次都会收到编译错误。

Thanks to Andreas感谢安德烈亚斯

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

or in your case或者在你的情况下

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM