So in Java, whenever an indexed range is given, the upper bound is almost always exclusive.
From java.lang.String
:
substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified
beginIndex
and extends to the character at indexendIndex - 1
From java.util.Arrays
:
copyOfRange(T[] original, int from, int to)
from
- the initial index of the range to be copied, inclusive
to
- the final index of the range to be copied, exclusive.
From java.util.BitSet
:
set(int fromIndex, int toIndex)
fromIndex
- index of the first bit to be set.
toIndex
- index after the last bit to be set.
As you can see, it does look like Java tries to make it a consistent convention that upper bounds are exclusive.
My questions are:
- Is this the official authoritative recommendation?
- Are there notable violations that we should be wary of?
- Is there a name for this system? (ala "0-based" vs "1-based")
CLARIFICATION: I fully understand that a collection of N
objects in a 0-based system is indexed 0..N-1
. My question is that if a range (2,4)
given, it can be either 3 items or 2, depending on the system. What do you call these systems?
AGAIN, the issue is not "first index 0
last index N-1
" vs "first index 1
last index N
" system; that's known as the 0-based vs 1-based system.
The issue is "There are 3 elements in (2,4)
" vs "There are 2 elements in (2,4)
" systems. What do you call these, and is one officially sanctioned over the other?