Is there an efficient method to remove a range - say the tail - of X elements from a List
, e.g. LinkedList
in Java?
It is obviously possible to remove the last elements one by one, which should result in O(X) level performance. At least for LinkedList
instances it should be possible to have O(1) performance (by setting the references around the first element to be removed and setting the head/tail references). Unfortunately I don't see any method within List
or LinkedList
to remove the last elements all at once.
Currently I am thinking of replacing the list by using List.subList()
but I'm not sure if that has equal performance. At least it would be more clear within the code, on the other hand I would loose the additional functionality that LinkedList
provides.
I'm mainly using the List as a stack, for which LinkedList
seems to be the best option, at least regarding semantics.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…