Casting and AutoboxingUnboxing in Expressions

本文详细解释了Java中的强制转换,包括普通转换、通过运算符的转换以及隐式转换(自动装箱与取消装箱)。文章讨论了不同类型的转换策略,尤其是在处理精度、对象引用和字符串连接时的注意事项。
摘要由CSDN通过智能技术生成

1.3.3 Casting and Autoboxing/Unboxing in Expressions

Casting is an operation that allows us to change the type of a value. In essence, we can take a value of one type and cast it into an equivalent value of another type. Casting can be useful for doing certain numerical and input/output operations.

强制转换是一种允许我们改变值的类型的操作。本质上,我们可以将一种类型的值强制转换为另一种类型的等价值。强制转换对于执行某些数值和输入/输出操作非常有用。

The syntax for casting an expression to a desired type is as follows:

(type)exp

where type is the type that we would like the expression exp to have. There are two fundamental types of casting that can be done in Java. We can either cast with respect to the base numerical types or we can cast with respect to objects. Here, we discuss how to perform casting of numerical and string types, and we discuss object casting in Section 2.5.1. For instance, it might be helpful to cast an int to a double in order to perform operations like division.

其中,type是我们希望表达式exp具有的类型。在Java中,可以进行两种基本类型的强制类型转换。我们可以对基本数值类型进行强制转换,也可以对对象进行强制转换。在这里,我们将讨论如何执行数值类型和字符串类型的强制转换,我们将在2.5.1章节讨论对象强制转换。例如,为了执行除法之类的操作,将int类型转换为double类型可能会很有帮助。

Ordinary Casting

When casting from a double to an int, we may lose precision. This means that the resulting double value will be rounded down. But we can cast an int to a double without this worry. For example, consider the following:

当从double类型转换为int类型时,我们可能会丟失精度。这意味,着产生的double值将向下舍入。但是我们可以将一个int类型转换为double类型,而不用担心这个问题。例如,请考虑以下情况:

double d1 = 3.2;
double d2 = 3.9999;
int i1 = (int)d1;        // i1 has value 3
int i2 = (int)d2;        // i2 has value 3
double d3 = (double)i2;  // d3 has value 3.0

Casting with Operators

Certain binary operators, like division, will have different results depending on the variable types they are used with. We must take care to make sure operations perform their computations on values of the intended type. When used with integers, division does not keep track of the fractional part, for example. When used with doubles, division keeps this part, as is illustrated in the following example:

某些二元运算符(如除法)将根据使用它们的变量类型而产生不同的结果。我们必须注意:确保操作在预期类型的值上执行计算。例如,当用于整数时,除法不保留小数部分。当与double一起使用时,除法保留小数部分,如下例所示:

int i1 = 3;
int i2 = 6;
dresult = (double)i1 / (double)i2; // dresult has value 0.5
dresult =i1 / i2;                  // dresult has value 0.0

Notice that when i1 and i2 were cast to doubles, regular division for real num- bers was performed. When i1 and i2 were not cast, the " /" operator performed an integer division and the result of i1 / i2 was the int 0. Then, Java did an implicit cast to assign an int value to the double result. We discuss implicit casting next.

注意,当 i1 和 i2 被转换为double时,执行实数的常规除法。当 i1 和 i2 没有强制转换时,“/”运算符执行整数除法,i1 / i2 的结果是 int 0. 然后,Java进行隐式强制转换,将int值赋给double结果。我们接下来将讨论隐式强制转换。

Implicit Casting and Autoboxing/Unboxing

There are cases where Java will perform an implicit cast, according to the type of the assignment variable, provided there is no loss of precision. For example:

在某些情况下,Java会根据赋值变量的类型执行隐式强制转换,前提是不丟失精度。举个例子:

int iresult, i = 3;
double dresult, d = 3.2;
dresult = i / d;       // dresult is 0.9375. i was cast to a double
iresult = i / d;       // loss of precision -> this is a compilation error
iresult = (int) i / d; // iresult is 0, since the fractional part is lost

Note that since Java will not perform implicit casts where precision is lost, the explicit cast in the last line above is required.

注意,由于Java不会在精度丢失的情况下执行隐式强制转换,因此需要执行上面最后一行中的显式强制转换。

Since Java SE 5, there is a new kind of implicit cast, for going between Number objects, like Integer and Float, and their related base types, like int and float. Any time a Number object is expected as a parameter to a method, the corresponding base type can be passed. In this case, Java will perform an implicit cast, called autoboxing, which wil convert the base type to its corresponding Number object. Likewise, any time a base type is expected in an expression involving a Number reference, that Number object is changed to the corresponding base type, in an operation called unboxing.

从Java SE 5开始,出现了一种新的隐式类型转换,用于在Number对象(如Integer和Float)和它们相关的基类型(如intfloat)之间转换。任何时候都需要Number对象作为方法的参数,都可以传递相应的基类型。在这种情况下,Java将执行一个隐式强制转换,称为自动装箱,它将把基类型转换为相应的Number对象。同样,每当需要在涉及Number引用的表达式中使用基类型时,该Number对象都会在名为取消装箱的操作中更改为相应的基类型。

There are a few caveats regarding autoboxing and unboxing, however. One is that if a Number reference is null, then trying to unbox it will generate an error, called NullPointerException. Second, the operator, “==”, is used both to test the equality of base type values as well as whether two Number references are pointing to the same object. So when testing for equality, try to avoid the implicit casts done by autoboxing and unboxing. Finally, implicit casts, of any kind, take time, so we should try to minimize our reliance on them if performance is an issue.

不过,关于自动装箱和拆箱有一些注意事项。一个是,如果一个Number引用为null,那么尝试将其取消装箱将生成一个错误,称为NullPointerException。其次,运算符“==”既用于测试基类型值是否相等,也用于测试两个Number引用是否指向同一个对象。因此,在测试相等性时,尽量避免通过自动装箱和取消装箱进行隐式强制转换。最后,任何类型的隐式强制类型转换都需要时间,因此如果性能是个问题,我们应该尽量减少对隐式强制类型转换的依赖。

Incidentally, there is one situation in Java when only implicit casting is allowed, and that is in string concatenation. Any time a string is concatenated with any object or base type, that object or base type is automatically converted to a string. Explicit casting of an object or base type to a string is not allowed, however. Thus, the following assignments are incorrect:

顺便说一句,在Java中有一种情况只允许隐式类型转换,那就是字符串连接。每当字符串与任何对象或基类型连接时,该对象或基类型将自动转换为字符串。但是,不允许将对象或基类型显式转换为字符串。因此,下列赋值语句是不正确的:

String s = (String) 4.5;             // this is wrong!
String t = "Value = " + (String) 13; // this is wrong!
String u = 22;                       // this is wrong!

To perform a conversion to a string, we must use the appropriate toString method or perform an implicit cast via the concatenation operation.

要执行到字符串的转换,我们必须使用适当的toString方法或通过串联操作执行隐式强制转换。

Thus, the following statements are correct:

因此,下列说法正确的是:

String s = "" + 4.5;             // correct, but poor style
String t = "Value = "+ 13;       // this is good
String u = Integer.toString(22); // this is good
  • 14
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值