Skip to content

Java ArrayList sublist example

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

How to get a sublist of ArrayList in Java?

Use the ArrayList subList method to get the sublist from ArrayList.

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

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 the end index is greater than the ArrayList size.

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

How to convert the sublist List object to ArrayList?

As you may have observed, subList method returns an object of the List instead of the ArrayList class. If you try to downcast the result of subList method to ArrayList object, you may get a 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 the 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 are also reflected in 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 a new element or removing element is a structural change as it changes the size of the list. If any structural changes are done to the sublist, they will be reflected in 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 the 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,

This example is a part of the ArrayList in Java tutorial.

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

About the author

2 comments

Leave a Reply

Your email address will not be published.