Why is array indexing in Java start with 0?

前端 未结 6 834
深忆病人
深忆病人 2020-12-01 15:06

Why is array indexing done with 0 and not with 1 in programming languages like Java ? I am totally new to java any explanation is welcomed.

6条回答
  •  离开以前
    2020-12-01 15:41

    To summarize his argument:

    When working with sub-sequences of natural numbers, the difference between the upper bound and the lower bound should be the length of the sub-sequence. The indices of an array can be thought of as a special kind of such a sub-sequence. The lower bound should be inclusive, the upper bound should be exclusive. In other words, the lower bound should be the first index of the array. Otherwise, we risk having to have a lower bound in the unnatural numbers for some sub-sequences. If we want to maintain conditions (1) and (2), then we effectively have two choices for upper and lower bounds: 1 <= i < N+1 or 0 <= i < N. Clearly, putting N+1 in the range is ugly, so we should prefer indexing starting from 0.

提交回复
热议问题