In general, yes. If you are working in a language with C-like syntax (C, C++, Java), then arrays are zero-indexed, and most random access data structures (vectors, array-lists, etc.) are going to be zero-indexed as well.
Starting indices at zero means that the size of the data structure is always going to be one greater than last valid index in the data structure. People often want to know the size of things, of course, and so it's more convenient to talk about the size than to talk about the the last valid index. People get accustomed to talking about ending indices in an exclusive fashion, because an array a[]
that is n
elements long has its last valid element in a[n-1]
.
There is another advantage to using an exclusive index for the ending index, which is that you can compute the size of a sublist by subtracting the inclusive beginning index from the exclusive ending index. If I call myList.sublist(3, 7)
, then I get a sublist with 7 - 3 = 4
elements in it. If the sublist()
method had used inclusive indices for both ends of the list, then I would need to add an extra 1 to compute the size of the sublist.
This is particularly handy when the starting index is a variable: Getting the sublist of myList
starting at i
that is 5 elements long is just myList.sublist(i, i + 5)
.
All of that being said, you should always read the API documentation, rather than assuming that a given beginning index or ending index will be inclusive or exclusive. Likewise, you should document your own code to indicate if any bounds are inclusive or exclusive.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…