为什么从指数是包容性的但最终指数是独家的? [英] why from index is inclusive but end index is exclusive?
问题描述
在Java API方法中,如:
In Java API methods like:
-
String.substring(int beginIndex,int endIndex)
-
String.subSequence(int beginIndex,int endIndex)
-
List.subList(int fromIndex,int toIndex)
String.substring(int beginIndex, int endIndex)
String.subSequence(int beginIndex, int endIndex)
List.subList(int fromIndex, int toIndex)
为什么是开头索引包容但最终索引独占?为什么他们不应该被设计为包容性?
Why is the beginning index inclusive but the end index exclusive? Why shouldn't they have been designed both inclusive?
推荐答案
因为:
- Java基于C,C就是这样做的
- 它使代码更清晰:如果要捕获到对象的末尾,则传递
object.length
(但是对象实现了这个,例如size()等)到toIndex参数中 - 不需要加/减1
- Java is based on C, and C does it this way
- It makes the code cleaner: If you want to capture to end of object, pass
object.length
(however the object implements this, eg size() etc) into the toIndex parameter - no need to add/subtract 1
例如:
String lastThree = str.substring(str.length() - 3, str.length());
这样,代码中发生的事情非常明显(好事)。
This way, it is very obvious what is happening in the code (a good thing).
编辑一个行为如此的C函数示例是来自<$ c的 strncat
$ c> string.h :
EDIT An example of a C function that behaves like this is strncat
from string.h
:
char *strncat(char *dest, const char *src, size_t n);
size_t
参数的值对应于java endPosition
参数,因为它们都是对象的长度,但如果它们是索引则从0开始计数,它将是超过对象末尾的一个字节。
The size_t
parameter's value corresponds to the java endPosition
parameter in that they are both the length of the object, but counting from 0 if they are the index, it would be one byte beyond the end of the object.
这篇关于为什么从指数是包容性的但最终指数是独家的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!