为什么在Java中op-assign运算符类型不安全? [英] Why aren't op-assign operators type safe in java?

查看:106
本文介绍了为什么在Java中op-assign运算符类型不安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定问题的措词是否明确,但举个例子会更清楚.

I'm not sure the question is clearly worded, but an example will be clearer.

我发现这在Java中不起作用:

I found out that will not work in Java:

int a = ...;
a = 5.0;

但这会:

int a = ...;
a += 5.0;

即,似乎=运算符是安全类型,而+ =则不是. 有什么深层原因吗?还是设计人员必须采取的另一种任意决定.

I.e., it seems that the = operator is type safe but += isn't. Is there any deep reason for this or is it just another arbitrary decision language designers must take.

推荐答案

使生活更轻松.

让我们走得更远.考虑:

Let's go a little further. Consider:

byte b;
...
++b;

增量实际上是在做:

b = (byte)(1 + (int)b);

即使使用+=,也不会变得更好:

Even using += it doesn't get any better:

b += b;

是:

b = (byte)((int)b+(int)b);

这将使这些运算符对字节/短/字符无效.

That would make these operators useless for byte/short/char.

在拥有任意大小的整数之前,我当然不会高兴.

Of course I wont be happy until we have arbitrary sized integers.

这篇关于为什么在Java中op-assign运算符类型不安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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