Search code examples
javalistarraylistsublist

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


I would have thought this question would have been answered before, but can't seem to find anything about it.

My question is as the title says, why does creating a sublist from index to index, not return the total number of indexes I'd expect?

A more detailed example:

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

I would expect the log to return 29 in the example above, but in actual fact it returns 28.

Why does this happen and what is the correct solution to this? To add +1 to the second index, or -1 to the first index?


Solution

  • It is clearly written in the documentation that sublist:

    public List subList(int fromIndex, int toIndex)

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

    To answer your question, as far as I understand, you might want to add +1 to the second parameter, because it is not included in the sublist.