Java简短加法问题 [英] Java Short addition questions

查看:40
本文介绍了Java简短加法问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能已经在另一篇文章中得到了回答,但是我只是不明白为什么我的测试Java应用程序(1.7.0_01)无法编译某些内容.

This may have already been answered in another post, but I just am not getting why something won't compile in my test Java app (1.7.0_01).

它将编译:

Short a = (short)17;
a = (short)2 + 1;

我知道"a + a"将产生一个整数.这样编译就可以了:

I know that "a + a" will result in an integer. This compiles fine:

Short a = (short)17;
int shortTest = a + a;

那为什么不编译呢?

Short a = (short)17;
a = (short)a + a;

此外,我是否可以假设由于转换为整数而不能在短裤上使用+ =,-=等...?如果可以进行这些操作,有人可以提供示例吗?

Also, am I right to assume you can't use +=, -=, etc... on Shorts because of the conversion to integer? If it's possible to do those operations, can someone provide an example?

编辑1
由于有人建议将它复制为原始类型'简短"-用Java进行转换.但是,我的示例围绕Wrapper的"Short"对象展开.围绕包装Wrapper对象有重要且更复杂的规则,这是我认为需要重点关注的规则.

Edit 1
There's been some votes to close this post as it's been suggested that it's a duplicate of Primitive type 'short' - casting in Java. However, my example revolves around the Wrapper "Short" object. There are important and more complicated rules around casting Wrapper objects and that's what I think needs to be focussed on.

而且,正如我的原始文章所指出的那样,我正在寻找第三个代码块后面的为什么" .我也想知道在短包装纸上是否可以使用"+ =",-="等.

Also, as my original post indicates, I'm looking for the "why" behind the 3rd code block. I'm also interested to know if it's possible to use "+=", "-=", etc... on the Short Wrapper.

推荐答案

由于某些原因,似乎删除了正确答案:(short)a + a 等同于((short)a)+ a ,您正在寻找(short)(a + a).

Seems the correct answer was removed for some reason: (short) a + a is equivalent to ((short) a) + a, you're looking for (short)(a + a).

其背后的原因"是运算符优先级> 1 + 2 * 3 7 ,而不是 9 .是的,基元和文字被视为相同.

The 'why' behind it is operator precedence, same reason why 1 + 2 * 3 is 7 and not 9. And yes, primitives and literals are treated the same.

你不能做 Short s = 1;s + = 1; ,因为它与 a = a + 1; 相同,其中a被转换为 int int 不能转换为 Short .您可以像这样修复长版本: a =(short)(a + 1); ,但是无法通过 + = 在其中进行显式转换.

You can't do Short s = 1; s += 1; because it's the same as a = a + 1; where a is converted to an int and an int can't be cast to a Short. You can fix the long version like so: a = (short) (a + 1);, but there's no way to get the explicit cast in there with +=.

这很烦人.

这篇关于Java简短加法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆