SATURN  RING  STATION

At a distant space view post, we chat about codes.

Java code example: Be careful with the potentially unexpected side effect of using ArrayList’s subList() method.

Return of ArrayList’s subList(…) method can be (case 1) assign directly to a List referent or (case 2) pass into a new List constructor then assign. Manipulating data in the new List with (1) doesn’t effect the original List, but it’s not true with (2).

 

Output:

 

According to this Java document.

SubList returns 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 supported by this list.

Leave a Comment

Your email address will not be published. Required fields are marked *

Java code example: Be careful with the potentially unexpected side effect of using ArrayList’s subList() method.