Collections

Java ArrayList sublist example

Java ArrayList sublist example shows how to get sublist of ArrayList in Java. Example also shows how to convert List object returned by sublist to ArrayList object.

How to get sublist of ArrayList in Java?

ArrayList class provides sublist method which can be used to get the sublist.

This method returns sublist containing elements between startIndex and endIndex. Please note that the startIndex is inclusive while endIndex is exclusive.

Java ArrayList sublist example

Output

Note:

ArrayList sublist method may throw IndexOutOfBoundsException if either of the index value specified is out of the range. That is, if the specified start index is less than 0 or end index is greater than the ArrayList size.

This method may also throw IllegalArgumentException if specified end index is greater than the start index. For example, sublist(7, 2) .

How to convert sublist List object to ArrayList?

As you may have observed, sublist method returns the List instead of ArrayList. If you try to downcast the result of sublist method to ArrayList object, you may get similar exception given below.

The preferred way is to always use Interface instead of casting it to the sub-class like ArrayList or LinkedList. But for any reason you want to cast List to ArrayList, you may use below given code.

Above approach uses ArrayList constructor to create a new ArrayList object from the List returned from the sublist method.

 
Important points to remember:

1)    Non-structural changes

Any change that does not alter the structure of the List, like modifying or replacing an element, is called non-structural change as it does not change the size of the list. The List returned by the sublist method is backed by the original ArrayList. Any non-structural changes to the original List is also reflected to the sublist like given below.

Output

Similarly, if you make any non-structural changes to the sublist, they will also be reflected back to the original list like given below.

Output

2)    Structural Changes

Any change that alters the structure of the List like adding new element or removing element are structural changes as it changes the size of the list. If any structural changes are done to the sublist, they will be reflected back to the original list as given below.

Output

Observe the position of element 99 in the original list. Since we added 99 at the end of the sublist, it is inserted after the last element of sublist in the original list as well.

Any structural changes done to the original list directly will invalidate the sublist. If any attempt is made to access the sublist after that, it will throw ConcurrentModificationException.

Will result in,

Please let us know your views in the comments section below.

Join 1000+ fellow learners! Enter your email address below: