I want to provide the actual page based on the entry index of a table's element. I use PageRequest.of(int page, int size)
.
I have the index
which is passed down to the function, and a constant PAGESIZE_SEARCH
which is 50.
I want to pass the current page according to the index as follows:
PageRequest.of((int) index/PAGESIZE_SEARCH, PAGESIZE_SEARCH)
My IDEA (IntelliJ Ultimate 2020.1.1) greys my casting out and hinting Casting 'index' to 'int' is redundant
. If I delete the cast even the compiler accepts it and I also don't get a Runtime Exception.
Why is this? Isn't the divsion unsafe there? Any explanation would be appreciated.
The division isn't unsafe; it does exactly as it should do.
Dividing two integers is known as an integer division and simply returns the result of dividing the two numbers without the remainder.
Also, as pointed out in the comments, you're actually casting index
to an int, rather than index/PAGESIZE_SEARCH
- think about using brackets to be more precise: (int) (index / PAGESIZE_SEARCH)
.
EDIT: You can read more on this topic here .
Mathematically speaking, the integers are not closed under divisison, meaning that the result of dividing two arbitrary integer like 3 and 5 may result in something that can not be represented by an integer. Each mathematical set of numbers (be it N, ℤ, ℚ, ℝ, ℂ) has certain limitations, and each of the representations of these sets in a computer has limitations as well. Understanding those limitations is a somewhat important point.
Wrt. division of two integers not being closed, you can deal with this in five different ways, mathematically speaking:
%
.The JLS specifies how division works in §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.
Moreover, you are not actually casting the result of the division to int
. You are only casting index
to an int
. The cast is irrelevant and redundant, because integer divisions returns an int
, as explained above.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.