当前位置: 动力学知识库 > 问答 > 编程问答 >

Create a "view" of a 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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: