为什么 ArrayList.subList(0, n) return 是一个大小为 n 的列表?

Why does ArrayList.subList(0, n) return a List of size n?

我原以为这个问题以前会有人回答,但似乎找不到任何相关信息。

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

更详细的例子:

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

我希望在上面的示例中日志为 return 29,但实际上它 returns 28.

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

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

public List subList(int fromIndex, int toIndex)

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

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

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

documentation

中所述

来自 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 参数是 "the index one past the one of the sublist"。 因此当你说 "stop at 48" 时,它实际上复制了项目 47 然后停止。

I would expect the log to return 29 in the example above

不是真的,根据 Doc

subList(int fromIndex, int 索引)

Returns a view of the portion of this list between the specified
fromIndex, inclusive, and toIndex, exclusive. (If
fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list

文档:

subList(int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

您所要求的一般用例是:

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

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

中的 toIndex

因此 subList(0,1) 将 return 一个只有一个元素的列表:第一个。

Sublist javadoc