Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a "view" of a Java List

Tags:

java

list

When doing something like

// creating list1, adding items
LinkedList slist = new LinkedList();
slist = subList(list1, 2,5);

I will have a second object (a "copy" of the elements 2 to 5 of "list") returned by subList and contained in slist. However, I would like to have something that only gives me a "view" of list1, without creating a new object and without allocating new memory, for performance/memory reasons.

like image 236
ptikobj Avatar asked Jan 12 '11 09:01

ptikobj


1 Answers

I think List#subList does exactly what you want:

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.

List slist = list1.subList(2, 5);

Of course, a new (wrapper) object needs to be created, but the data structure for the list, and all the elements will be re-used. The wrapper just keeps track of the start and end pointers.

like image 87
Thilo Avatar answered Nov 12 '22 05:11

Thilo