gpt4 book ai didi

java - 处理短数据类型的变量

转载 作者:行者123 更新时间:2023-12-01 17:23:40 25 4
gpt4 key购买 nike

我有一个方法,其中我收到的参数是“rowno”,其类型为短。代码如下所示。

private int abcd (int a , short rownum)
{
// method body
}

现在我的查询是这样的。在方法内部,当以下值时,我必须执行一些逻辑rownum 是 5 ,所以我尝试这样

if (rowno == 5)
{
//perform some operation

}

请告诉我这是否是短类型的正确方法。

最佳答案

这应该可以正常工作。

rownoshort 时,表达式 rowno == 5 相当于 ((int) rowno) == 5 因为 Java 隐式提升了原始操作数。

Java Language Specification

5.6.2. Binary Numeric Promotion

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

2 Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

Binary numeric promotion is performed on the operands of certain operators:

...

  • The numerical equality operators == and !=

根据

,此处发生的转换是安全的

5.1.2. Widening Primitive Conversion

19 specific conversions on primitive types are called the widening primitive conversions:

  • ...
  • short to int, long, float, or double
  • ...

A widening primitive conversion from an integral type to another integral type, or from float to double in a strictfp expression (§15.4), does not lose any information at all; the numeric value is preserved exactly.

关于java - 处理短数据类型的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16663604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com