Truncate a LinkedList

Peter Levart peter.levart at
Tue Feb 19 12:24:09 UTC 2013

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, that
>> 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?
>> Thanks
>> Max
> Hi Max,
> You could try to use AbstractList.subList(...)
> <,%20int%29> 
> Quoting from the doc:
>> For example, the following idiom removes a range of elements from a 
>> list:
>>       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...

Regards, Peter

> -- daniel

More information about the core-libs-dev mailing list