Radu
Radu

Reputation: 1104

java list implementation

I have the following use case:

I wanted to ask what would be the best list implementation for this situation given the fact that I need to do operations on the list such as

Thanks.

Upvotes: 1

Views: 710

Answers (3)

Aravind Yarram
Aravind Yarram

Reputation: 80176

A single collection type can't satisfy all of those use-cases. The nearest I can see is TreeSet.

  • order - Implement your object to override equals and hascode based on type
  • sublists - headSet, tailSet
  • filtering - roll your won

Upvotes: 0

Alexander Pavlov
Alexander Pavlov

Reputation: 32286

java.util.ArrayList seems best in this case (backed up by a vector). One thing that you need to do upfront is reserve enough space when constructing the instance (it's best if you know the number of elements beforehead), to avoid copying on resized vector allocations.

Another win compared to LinkedList is the absense of internode references which reduces the required heap size roughly twice compared to ArrayList.

  • append: O(1) (given no inserts)
  • ordering = sorting: O(n*log(n))
  • filtering: O(n)
  • sublist: O(1)

Upvotes: 0

Savvas Dalkitsis
Savvas Dalkitsis

Reputation: 11592

If you know the size of the list (or an upper bound) before-hand and can guarantee no insertions then you need to use ArrayList.

It is backed up by an array so lookups are fast.

Upvotes: 2

Related Questions