Home > database >  Java - ArrayList method for a sublist including the last element?
Java - ArrayList method for a sublist including the last element?

Time:10-20

For a sublist of an ArrayList, how do I get the sublist including the last element in the list? If I'm using the wrong method, can you direct me towards the correct one?

list.subList(startIndex, index   list.size()) // obviously doesn't work, outside of range
list.sublist(startIndex) // doesn't work because this method requires two parameters

CodePudding user response:

You can find the correct method including a description in the JavaDoc:

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/AbstractList.html#subList(int,int)

public List<E> subList(int fromIndex,
                       int toIndex)

With this method, you can create a new list including all the elements from an existing list, you want to have in your new list.

Example: final var newList = oldList.subList(7, oldList.size());

This will create a new list containing the objects from position 8 to the end of the old list.

  • Related