I've met a such kind of code and comments in the java.util.ImmutableCollections
class:
static final class List0<E> extends AbstractImmutableList<E> {
...
@Override
public E get(int index) {
Objects.checkIndex(index, 0); // always throws IndexOutOfBoundsException
return null; // but the compiler doesn't know this
}
...
}
Why not just throw new IndexOutOfBoundsException(...)
? What's the reason?
Perhaps, it is just an avoiding of a code duplication, because otherwise it would be something like:
new IndexOutOfBoundsException(outOfBoundsMessage(..., ...))
but outOfBounds*
methods are private
, so by design somebody should call wrappers like return Preconditions.checkIndex(index, length, null)
The implementation seems more design-oriented than just functionality here.
The reasons for the same could primarily be that the Preconditions.checkIndex
is marked as an @HotSpotIntrinsicCandidate
which means a code performance improvement is sought while this method is used internally.
Also, can notice that all the immutable list - containing 0(empty),1, 2 or N elements, created using the factory method of
makes use of the Objects.checkIndex(int index, int length)
which eventually relies on the above method call to possibly make some internal optimisations.
Brief over HotSpotIntrinsicCandidate
from the library :-
The
@HotSpotIntrinsicCandidate
annotation is specific to the HotSpot Virtual Machine. It indicates that an annotated method may be (but is not guaranteed to be) intrinsified by the HotSpot VM.A method is intrinsified if the HotSpot VM replaces the annotated method with hand-written assembly and/or hand-written compiler IR -- a compiler intrinsic -- to improve performance.
The
@HotSpotIntrinsicCandidate
annotation is internal to the Java libraries and is therefore not supposed to have any relevance for application code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With