Which data structure for sorting a list of numbers and associated objects?
Joined: Sep 10, 2004
Okay, now I have yet another question. I am trying to solve a simple problem. I have pairs of values in my TreeMap right now. I'm not sure I'm using the right data structure at all. I put them in a TreeMap because it allows you to maintain the mapping between two values and also to sort on the keys. What I have done so far is to sort the TreeMap and print it all out. I did this with code that uses and iterator that I found online. I don't totally understand it. I read the javadocs on iterators, though, but there doesn't seem to be an answer there. What I want to do is assign the values in the last five elements of the TreeMap to individual variables so that I can use them elsewhere. But how do you get at "last five" in a TreeMap? I see there's a method for getting the last element and one for removing an element. So I could theoretically get the last one and remove it five times. But that seems a little tacky. Is there a better way using the iterator? Am I even using the appropriate data structure? This is a really simple problem that seems to have an elusive answer. Thanks for any ideas, Rebecca
Joined: Nov 11, 2004
well what i would do is just biggy bag one of your other loops. Like your print function. or your search function. While your in one of those loops set your variables.
so like if you have for(int i=0; i<length; i++) //print function if i is 5 away from the end var1 = value var2 = value
or whatever. the logic is there (i think) just fill in the langauge parts
thats how id' do it, then again i'm in the beginer section for a reason
Joined: Jan 29, 2003
Take a look at the keySet() method. What does that return? Look at that class. Can you turn the keySet into something that makes it easier to get the last 5?
Is your assignment "the last 5" or "the 5 highest keys" ? If it's the latter, look at all the TreeSet constructors. You could make the TreeSet sort backwards, and then take the first 5!
I can think of one other really inefficient way to do this. I'm sure there are more. Let us know what you come up with!
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi