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

查看:44
本文介绍了为什么 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:

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

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

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

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