possible lossy conversion from int to short

后端 未结 1 598
难免孤独
难免孤独 2021-01-19 04:05

I have defined array gx, array arr to be short type. but why the operation at left may end up with int type and I must cast it into short? the compiler error is possible los

相关标签:
1条回答
  • 2021-01-19 04:22

    It's not unboxing; it's "binary numeric promotion". Section 5.6.2 of the JLS states:

    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:

    1. If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

    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.

    and

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

    • The multiplicative operators *, /, and % (§15.17)

    • The addition and subtraction operators for numeric types + and - (§15.18.2)

    • The numerical comparison operators <, <=, >, and >= (§15.20.1)

    • The numerical equality operators == and != (§15.21.1)

    • The integer bitwise operators &, ^, and | (§15.22.1)

    • In certain cases, the conditional operator ? : (§15.25)

    (emphasis mine)

    When those values are added/multiplied, they are promoted to int before the math is done. At the end, you can cast back to short before assigning back to the array.

    gx[x][y][z] = (short) (arr[x-1][y-1][z]-arr[x+1][y-1][z]+2*arr[x-1][y][z]
        -2*arr[x+1][y][z]+arr[x-1][y+1][z]-arr[x+1][y+1][z]);
    

    You will need to cast it back every time you operate with primitive data types that are smaller than int, such as in your short example.

    0 讨论(0)
提交回复
热议问题