有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么这些案例不返回IndexOutofBoundsException?

我最近偶然发现了这一点。为什么以下情况不返回IndexOutofBoundsException

public static void main(String[] args) {
    String str = "String";
    System.out.print(str.substring(0, 0));
}

public static void main(String[] args) {
    String str = "String";
    System.out.print(str.substring(str.length()));
}

我一直被告知这一点。子字符串(inti,intk)返回从索引i到k-1的子字符串。在第一种情况下,子字符串不是从索引0到-1吗?为什么这不会产生越界错误?我也有同样的问题。长度()的情况下,以及


共 (3) 个答案

  1. # 1 楼答案

    Java 8 API开始:

    public String substring(int beginIndex, int endIndex)
    

    Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

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

    是阴性吗?不,是0
    endIndex是否大于字符串的长度?不,0<;6.
    beginIndexendIndex大吗?不,他们都是0

    I have the same question with the .length() case as well.

    你为什么期望它抛出异常length()从不扔

  2. # 2 楼答案

    看看substring javadoc

    Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

    因此,"String".substring(0, 0)只返回空字符串""

    看看length javadoc

    Returns the length of this string. The length is equal to the number of Unicode code units in the string.

    因此"String".length()返回5

  3. # 3 楼答案

    StringJavaDoc表示IndexOutOfBoundsException将被抛出,如果:

    the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

    您的示例不符合任何这些标准,因此不会引发异常。如果开始索引和结束索引相等,结果总是得到一个空的String

    对于第二个例子,我不太确定你的问题是什么.length()只返回String包含的字符数。在上面的示例中,它只返回int6