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.
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.
精彩评论