What Java data structure should I use

lozina

Lifer
Sep 10, 2001
11,711
8
81
I need to have a sorted list of elements limited to a certain size.

At first I used a SortedSet - TreeSet to be exact. And this kept my elements sorted as I inserted them but I cannot easily remove the last element, because it's remove method only accepts an Object reference, not an index like I hoped.

See what I want to do is maintain a top 10 list of alphabetically ordered elements from a certain query. As I process each result of the query I add them to the TreeSet (which inserts it in the appropriate order) then if the resulting size is >10 I wanted to remove the 11th element but I cant do this with TreeSet.

Obviously, I cannot just ignore any additional elements once I reach 10 in my TreeSet because the later elements may turn out to take a higher rank in the list based on alphabetical order than what's already inside, which would cause an existing element to be removed instead.
 

Crusty

Lifer
Sep 30, 2001
12,684
2
81
Can't you just do

myTreeSet.remove(myTreeSet.last());

?

edit:

In fact, you could just extend the TreeSet class yourself to take a max size and have it automatically trim the Tree to keep it at max size or less. You would only have to overload a few functions :)
 

lozina

Lifer
Sep 10, 2001
11,711
8
81
Oh nice, didn't realize TreeSet had that method! I was actually looking at it's superclass Set - stupid me!

thanks!