Java – why are indexes inclusive but exclusive?

In Java API methods, such as:

> String. substring(int beginIndex,int endIndex) > String. subSequence(int beginIndex,int endIndex) > List. subList(int fromIndex,int toIndex)

Why does the start index contain but the end index is exclusive? Why shouldn't they be designed to be inclusive?

Solution

Because:

>Java is based on C, which does this > it makes the code cleaner: if you want to capture the end of the object, put the object Length (but the object implements this, such as size ()) is converted to the toindex parameter – you don't need to add / subtract 1

For example:

In this way, it's clear what's going on in the code (a good thing)

An example of editing a C function like this is from string Strncat of H:

size_ The value of the T parameter corresponds to the Java endposition parameter because they are the length of the object, but if they are indexes, count from 0, which will be a byte beyond the end of the object

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>