8

I am looking for a data structure implementing List that allows me to reuse parts of the list occurring in multiple lists.

To illustrate this consider the following three lists:

enter image description here

As you can see, the red sequence (42, 88, 76, 60) and the blue sequence (21, 9, 47) are used multiple times, each representing an independent List shared as part of other lists. In reality, the lists could be much longer.

The list only needs to be read-only as it will be used as a return value. The procedure creating the collection of lists will be the only one (allowed to) to modify the list (use add(..) operations etc.). Sharing parts of the lists will make it redundant to expansively copy list elements using addAll(..) (which internally uses System.arraycopy(..)).

Are there any light-weighted List implementations out there to fulfill my needs? Or is there a relatively simple way of implementing one myself?

Frithjof
  • 2,214
  • 1
  • 17
  • 38
  • Is the procedure creating the collection of lists aware of the reusable parts, or is it expected to discover them itself? – jaco0646 Feb 09 '16 at 21:23
  • 1
    Does it actually need to be a List? What parts of the List api do the consumers of this collection of lists care about, and do you control what parameter type they declare? There are easy solutions for Iterable (if the consumers only iterate through) or Set (if order is irrelevant), and even MultiSet (order is irrelevant but multiples are allowed), but List seems to be missing for this capability. – Douglas Feb 09 '16 at 21:29
  • @jaco0646 The procedure is aware of the reusable parts, as if `addAll(reusablePart)` would be called. – Frithjof Feb 09 '16 at 21:38
  • @Douglas Consumers would mainly want to iterate over the list, and perhaps random access it (but that's not the main concern). – Frithjof Feb 09 '16 at 21:41

1 Answers1

2

For Iterable, Set, and Multiset, Guava has you covered with Iterables.concat(), Sets.union(), and Multisets.sum() respectively. Lists, unfortunately, lacks the equivalent method.

Douglas
  • 5,017
  • 1
  • 14
  • 28