gpt4 book ai didi

java - 为什么 from index 是 inclusive 而 end index 是 exclusive?

转载 作者:太空狗 更新时间:2023-10-29 22:55:08 26 4
gpt4 key购买 nike

在 Java API 方法中,如:

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

为什么开始索引包含但结束索引不包含?为什么不应该将它们设计成兼具包容性?

最佳答案

因为:

  • Java是基于C的,C是这样做的
  • 它使代码更简洁:如果你想捕获到对象的末尾,将 object.length (但是对象实现了它,例如 size() 等)传递到 toIndex 参数中 - 不需要加/减 1

例如:

String lastThree = str.substring(str.length() - 3, str.length());

这样,代码中发生的事情就很明显了(好事)。

编辑 string.h 中的 strncat 是 C 函数的一个例子:

char *strncat(char *dest, const char *src, size_t n);

size_t 参数的值对应于 java endPosition 参数,因为它们都是对象的长度,但从 0 开始计数,如果它们是索引,它将是对象末尾之外一个字节。

关于java - 为什么 from index 是 inclusive 而 end index 是 exclusive?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6339158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com