The subList() method of java.util.CopyOnWriteArrayList class is used to return 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.
public List subList(int fromIndex, int toIndex)
Parameters: This method takes the following argument as a parameter.
- fromIndex – low endpoint (inclusive) of the subList
- toIndex – high endpoint (exclusive) of the subList
Returns Value: This method returns a view of the specified range within this list.
Exception: This method throws IndexOutOfBoundsException if an endpoint index value is out of range (fromIndex size)
Below are the examples to illustrate the subList() method.
Original arrlist: [A, B, C, D, E] Sublist of arrlist: [C, D]
Example 2: For IndexOutOfBoundsException
Original arrlist: [A, B, C, D, E] End index value is out of range Exception thrown: java.lang.IndexOutOfBoundsException
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.