Truncate a LinkedList
peter.levart at gmail.com
Tue Feb 19 12:36:12 UTC 2013
On 02/19/2013 01:24 PM, Peter Levart wrote:
> On 02/19/2013 11:38 AM, Daniel Fuchs wrote:
>> On 2/19/13 11:27 AM, Weijun Wang wrote:
>>> Hi All
>>> I'm using LinkedList to maintain a history and the elements are ordered
>>> by their timestamps. Every now and then I would "expunge" the list,
>>> is to say, iterating through the list and when an element is old enough
>>> all elements after (and including) it will be removed. Currently I'm
>>> removing them one by one.
>>> Is there a way to truncate the list using a single method?
>> Hi Max,
>> You could try to use AbstractList.subList(...)
>> Quoting from the doc:
>>> For example, the following idiom removes a range of elements from a
>>> list.subList(from, to).clear();
> Hi Daniel,
> That's not terribly efficient. It does the list.removeRange(from, to)
> which iterates the list again from the beginning to "from" followed by
> iterating elements further to "to" while removing elements one-by-one.
> That's worse than Weijun's original algorithm which iterates the
> elements from 1st to "from" only once.
> I would make my own linked structure for that task, but if you want to
> stick with LinkedList, your expunging algorithm could "copy" the
> elements, from the 1st to the one that is the last to be kept, into a
> new LinkedList and then just exchange the old list with the new...
The above would be efficient if the remaining "head" is small compared
to the discarded "tail". If it's the other way around, you could iterate
the LinkedList from the end backwards and remove the elements along the
way until you reach the one you want to keep...
> Regards, Peter
>> -- daniel
More information about the core-libs-dev