如果结果必须是 int,为什么 Java 编译器允许 int/int 除法?

Why does the Java compiler allow int/int division if the result must be an int?

我想根据 table 元素的条目索引提供实际页面。我用 PageRequest.of(int page, int size).

我有传递给函数的 index 和一个常量 PAGESIZE_SEARCH,即 50。

我想根据索引传递当前页面如下:

PageRequest.of((int) index/PAGESIZE_SEARCH, PAGESIZE_SEARCH)

我的 IDEA (IntelliJ Ultimate 2020.1.1) 将我的铸造和提示变灰 Casting 'index' to 'int' is redundant。如果我删除强制转换,即使编译器接受它,我也不会得到运行时异常。

这是为什么?那里的分区不安全吗?任何解释将不胜感激。

这个部门并不安全;它完全按照它应该做的去做。

两个整数相除被称为整数除法,简称returns两个数相除没有余数的结果。

此外,正如评论中指出的那样,您实际上是将 index 转换为 int,而不是 index/PAGESIZE_SEARCH - 考虑使用括号更精确:(int) (index / PAGESIZE_SEARCH) .

编辑:您可以阅读有关此主题的更多信息 here

从数学上讲,整数在除法下是不封闭的,这意味着将两个任意整数(例如3和5)相除的结果可能会导致无法用整数表示的结果。每个数学数字集(无论是 N、ℤ、ℚ、ℝ、ℂ)都有一定的局限性,并且这些集合在计算机中的每个 表示 也有局限性。理解这些限制是一个有点重要的点。

Wrt。两个整数的除法不闭合,你可以用五种不同的方式处理这个问题,从数学上讲:

  • 使除法成为偏函数。对于必须处理任意输入的编程语言来说,这是不可取的。每次尝试对未定义除法的数字进行除法时,是否都会出现算术异常?这不是一个好方法。
  • 做一个从整数到实数的除法函数。这实际上是一种你可以使用的方法,但是实数不能在计算硬件中精确表示,所以它只能是近似解。以这种方式实现编程语言当然是可能的,但实际上您更可能对整数结果感兴趣。
  • 以分数形式给出答案 (Q)。例如3/5 变为⅗,有时表示为元组 (3,5)。你可以用某些编程语言做这样的事情,例如Haskell.
  • 以商和余数形式给出答案。一些编程语言会这样做,但是 Java 不支持元组类型,也不支持多个 return 值,所以这已经过时了。这有时被称为 欧氏除法 .
  • 只给出商作为答案,舍弃余数。这通常称为 整数除法 ,并且是 Java 实现的。您可以通过相关操作恢复余数,模运算符 %.

JLS 指定除法在 §15.7.2 中的工作方式:

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d ⋅ q| ≤ |n|. Moreover, q is positive when |n| ≥ |d| and n and d have the same sign, but q is negative when |n| ≥ |d| and n and d have opposite signs.

There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

此外,您实际上并没有将除法的结果转换为 int。您 index 转换为 int。转换是无关紧要和多余的,因为整数除法 return 是 int,如上所述。