【问题标题】:Why does ArrayList.subList(0, n) return a List of size n?为什么 ArrayList.subList(0, n) 返回一个大小为 n 的列表?
【发布时间】:2016-05-16 14:40:56
【问题描述】:

我本以为这个问题以前会得到回答,但似乎找不到任何关于它的信息。

我的问题是正如标题所说,为什么创建一个从索引到索引的子列表,而不是返回我期望的索引总数?

更详细的例子:

List slice = points.sublist(20, 48);
Log.i(TAG, slice.size());

我希望在上面的示例中日志返回 29,但实际上它返回 28。

为什么会发生这种情况,正确的解决方案是什么?要将 +1 添加到第二个索引,还是将 -1 添加到第一个索引?

【问题讨论】:

    标签: java list arraylist sublist


    【解决方案1】:

    documentation那个子列表里写得很清楚:

    公共列表子列表(int fromIndex, int toIndex)

    返回此列表在指定之间的部分的视图 fromIndex,包含,toIndex,排除。

    要回答您的问题,据我了解,您可能需要将+1 添加到第二个参数,因为它不包含在子列表中。

    【讨论】:

    • 看来我当时很笨。我多次检查文档并错过了似乎“独家”这个词......谢谢。
    • @nineteeneightyeight 如果您检查了文档,我建议您将其作为您所做的研究放在问题中。首先,在撰写研究报告时,您更有可能在文档中看到此注释。其次,如果它像您在发布问题之前所做的研究一样成功,那么它不太可能被否决。
    【解决方案2】:

    文档:

    subList(int fromIndex, int toIndex) 返回此列表在指定 fromIndex,inclusive 和 toIndex,exclusive 之间部分的视图。

    您所要求的一般用例是:

    points.sublist(20, points.size());
    

    【讨论】:

      【解决方案3】:

      第一个索引是包含的,另一个是排除的。 a.subList(0,n) 返回一个包含元素 0,1,2,...,n-1 的列表

      documentation中所述

      【讨论】:

        【解决方案4】:

        在上面的示例中,我希望日志返回 29

        不是真的,根据Doc

        subList(int fromIndex, int toIndex)

        返回此列表在指定
        之间的部分的视图 fromIndex(包括)和 toIndex(不包括)。 (如果
        fromIndex 和 toIndex 相等,返回列表 是空的。)返回的列表是由这个列表支持的,所以 返回列表中的非结构性变化反映在此 列表,反之亦然。返回的列表支持所有可选的 列出此列表支持的操作

        【讨论】:

          【解决方案5】:

          来自subList的文档:

          /**
           * Returns a {@code List} of the specified portion of this {@code List} from the given start
           * index to the end index minus one. The returned {@code List} is backed by this
           * {@code List} so changes to it are reflected by the other.
           *
           * @param start
           *            the index at which to start the sublist.
           * @param end
           *            the index one past the end of the sublist.
           * @return a list of a portion of this {@code List}.
           * @throws IndexOutOfBoundsException
           *                if {@code start < 0, start > end} or {@code end >
           *                size()}
           */
          public List<E> subList(int start, int end);
          

          如您所见,end 参数是“子列表之后的索引”。 因此,当您说“在 48 处停止”时,它实际上会复制项目 47 然后停止。

          【讨论】:

            【解决方案6】:

            考虑到 javadoc 在这一点上非常清楚,提取的子列表包括 fromIndex 并且不包括 List.subList(fromIndex, toIndex) 中的 toIndex

            因此 subList(0,1) 将返回一个仅包含一个元素的列表:第一个元素。

            Sublist javadoc

            【讨论】:

              猜你喜欢
              • 2018-04-14
              • 2020-03-19
              • 2014-07-20
              • 2015-01-27
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-05-04
              相关资源
              最近更新 更多