String is to Substring, as ArrayList is to?

11,956

Solution 1

This method is called subList and exists for both array and linked lists. Beware that the list it returns is backed by the existing list so updating the original one will update the slice.

Solution 2

The answer can be found in the List API: List#subList(int, int) (can't figure out how to get the link working....)

Be warned, though, that this is a view of the underlying list, so if you change the original list, you'll change the sublist, and the semantics of the sublist is undefined if you structurally modify the original list. So I suppose it isn't strictly what you're looking for...

If you want a structurally independent subsection of the list, I believe you'll have to do something like:

ArrayList<something> copy = new ArrayList<>(oldList.subsection(begin, end));

However, this will retain references to the original objects in the sublist. You'll probably have to manually clone everything if you want a completely new list.

Share:
11,956
Quinn McHugh
Author by

Quinn McHugh

Updated on June 04, 2022

Comments

  • Quinn McHugh
    Quinn McHugh almost 2 years

    In Java, and many other languages, one can grab a subsection of a string by saying something like String.substring(begin, end). My question is, Does there exist a built-in capability to do the same with Lists in Java that returns a sublist from the original?