为什么不List.subList(size,size)上的IndexOutOfBoundsException? [英] Why not IndexOutOfBoundsException on List.subList(size, size)?

查看:154
本文介绍了为什么不List.subList(size,size)上的IndexOutOfBoundsException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看List.subList()方法.我想知道为什么以下代码不会引发IndexOutOfBoundsException.

I was looking at the List.subList() method. I wondered why the following code doesn't throw an IndexOutOfBoundsException.

ArrayList<String> someList = new ArrayList<>();
someList.add("A");
someList.add("B");
someList.add("C");
someList.add("D");
someList.add("E");

someList.subList(5, 5);

文档说subList是subList(fromIndex,toIndex),其中fromIndex包含在内.因为我的list.size()是5,所以索引从0到4.所以,如果fromIndex是包容性的,不应该抛出异常吗?

The docs says subList is subList(fromIndex, toIndex), where fromIndex is inclusive. Since my list.size() is 5, the indexes goes from 0 to 4. So if fromIndex is inclusive, shouldn't an Exception be thrown?

从文档中

fromIndex - low endpoint (inclusive) of the subList
toIndex - high endpoint (exclusive) of the subList

IndexOutOfBoundsException - for an illegal endpoint index value (fromIndex < 0 || toIndex > size || fromIndex > toIndex)

我在这里了解布尔表达式.但这不是(... || fromIndex> = toIndex)吗?

I understand the boolean expression here. But shouldn't it be (... || fromIndex >= toIndex)?

我想念什么?

推荐答案

您可以确切地检查 ArrayList 的实现,其中IndexOutOfBoundsException的标准是:

You can check the implementation of ArrayList exactly what the criteria for IndexOutOfBoundsException are:

public List<E> subList(int fromIndex, int toIndex) {
    subListRangeCheck(fromIndex, toIndex, size);
    return new SubList(this, 0, fromIndex, toIndex);
}

static void subListRangeCheck(int fromIndex, int toIndex, int size) {
    if (fromIndex < 0)
        throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
    if (toIndex > size)
        throw new IndexOutOfBoundsException("toIndex = " + toIndex);
    if (fromIndex > toIndex)
        throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                           ") > toIndex(" + toIndex + ")");
}

因此您可以看到,由于 toIndex == size ,因此不会引发异常.

So you can see, since toIndex == size, exception is not thrown.

要考虑API设计者为何决定采用这种方式的决定,我们可以举一个 String.substring()为例,它具有非常相似(相同)的约束.可能允许选择一个空的字符串/子列表?

To contemplate the decision of API designers why they decided to do it this way, we may take as an example String.substring(), which has very similar (the same) constraints. Possibly to allow to select an empty string/sublist?

此外,文档证实了这一假设:

Also, the documentation confirms this assumption:

(如果 fromIndex toIndex 相等,则返回的列表为空.)

(If fromIndex and toIndex are equal, the returned list is empty.)

这篇关于为什么不List.subList(size,size)上的IndexOutOfBoundsException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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