【问题标题】:Why not IndexOutOfBoundsException on List.subList(size, size)?为什么不在 List.subList(size, size) 上出现 IndexOutOfBoundsException?
【发布时间】:2017-04-19 18:51:23
【问题描述】:

我正在查看 List.subList() 方法。我想知道为什么下面的代码没有抛出 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 包含在内,不应该抛出异常吗?

来自文档:

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) 吗?

我错过了什么?

【问题讨论】:

  • subList(0,0) 呢?
  • 长度为0的列表没有问题,如果fromIndex总是小于toIndex那是不可能的,你认为不应该允许用例吗?
  • 他们决定以这种方式构建规范,如果您有 fromIndex == toIndex,则允许空子列表。这是他们做出的明确设计决定,具有很多优势。
  • 我想象一个类似 for 循环的情况:int i = fromIndex; i &lt; toIndex; i++,但循环永远不会运行,因为条件在开始时已经为假。不过,您可以随时检查来源以确保。
  • doesn't Java try to fetch the item - Java 在这里不获取任何东西。 subList 返回原始列表的视图

标签: java list arraylist


【解决方案1】:

您可以检查ArrayList 的实现,IndexOutOfBoundsException 的标准是什么:

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,没有抛出异常。

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

另外,the documentation 证实了这一假设:

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

【讨论】:

  • "但不应该是(... || fromIndex &gt;= toIndex)吗?"
  • @BoristheSpider 这不取决于 API 设计者吗?我们该向谁提问?
  • 我们是 API 的用户,我们正是质疑其设计者的人。
  • @BoristheSpider 好的,这对我来说是个小玩笑。我的观点是,一旦 API 出来,就无法更改。所以关于它是否正确的争论似乎有点毫无意义。至少在这里,在stackoverflow上......
  • 当然规范是正确的。如果指定为... fromIndex &gt;= toIndex),则不正确。
猜你喜欢
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
  • 2018-04-12
  • 2020-09-22
  • 2022-07-22
  • 2014-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多