Java - 为什么 str.substring(str.length()) 是可接受的代码行? [英] Java - Why is str.substring(str.length()) an acceptable line of code?

查看:20
本文介绍了Java - 为什么 str.substring(str.length()) 是可接受的代码行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长话短说,为什么 Java 不为这行代码抛出 IndexOutOfBoundsException?

To make a long story short, why does Java not throw an IndexOutOfBoundsException for this line of code?

str.substring(str.length())

是否只是根据 IndexOutOfBoundsException 的定义?为了编程方便/对称,使开始/结束索引采用相同的值范围?这只是甲骨文的决定吗?引擎盖下是否只有一种特殊情况可以使用包含开始索引来处理这种情况?或者有什么潜在的原因...

Is it just by definition of IndexOutOfBoundsException? To make start/end indices take the same range of values for programming convenience/symmetry? Is it just a decision by Oracle? Is there just a special case under the hood that handles this case with the inclusive start index? Or is there some underlying reason...

我阅读了文档,他们说它只返回空字符串 ("").但我想知道这是否值得担心.它会永远改变吗?我想不,但我想听听别人的意见.我有一些代码依赖于这样的行才能工作,因为我使用 substring 和 indexOf(...)+1 来拆分一些行,而且我真的不想在代码行周围放置不必要的逻辑.

I read the documentation and they say it just returns the empty string (""). But I'm wondering if this is something to worry about. Will it ever change? I'm thinking no, but I'd like to hear it from someone else. I have some code that depends on a line like this to work because I use substring and indexOf(...)+1 to split some lines up, and I really don't want to put unnecessary logic around the line of code.

推荐答案

这是 substring(beginindex) javadoc 的文档.

Here´s the docu of the substring(beginindex) javadoc.

返回一个新字符串,它是该字符串的子字符串.子字符串从指定索引处的字符开始,并延伸到该字符串的末尾.

Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

示例:

"unhappy".substring(2) 返回 "happy"

"unhappy".substring(2) returns "happy"

"Harbison".substring(3) 返回 "bison"

"Harbison".substring(3) returns "bison"

"emptiness".substring(9) 返回 ""(空字符串)

"emptiness".substring(9) returns "" (an empty string)

参数:beginIndex 开始索引,包括在内.

Parameters: beginIndex the beginning index, inclusive.

返回:指定的子串.

抛出:IndexOutOfBoundsException - 如果 beginIndex 为负数或大于此 String 对象的长度.

Throws: IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

主要是因为它只是在 beginindex > 时抛出.length 并且如果 beginindex == length 将返回一个空的 String.

Basicly because it just throws if beginindex > length and will return an empty String if beginindex == length.

正如@Kayaman 指出的那样,Oracle 不会为了改变这一点而破坏对其他 Java 版本的向后兼容性.

And as @Kayaman pointed out, Oracle wont destroy the backward compatibility to other java version just to change this.

这篇关于Java - 为什么 str.substring(str.length()) 是可接受的代码行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆