a collection problem with TreeMap
Could somebody please help me with this kind of problem
I couldn't get the correct object from the get(key) method and all the objects in the map become the last object put in, when I use the followings:
Collection keys=this.keySet();
Iterator iter=keys.iterator();
while(iter.hasNext())
{
XX xx=(XX)this.get(iter.next());
...
}
But when I try to iterate the values instead of the keys, the objects are correct.
Collection values=this.values();
Iterator iter=values.iterator();
while(iter.hasNext())
{
XX xx=(XX)iter.next();
...
}
But I do need the get(key) method sometimes.
Anybody got some suggestions please.
Thanks.
[743 byte] By [
gnosa] at [2007-11-27 8:20:46]

# 2
My Key class is like this, Could you see any problem from it? Thanks.
import java.lang.Comparable;
public class TreeKey implements Comparable {
private int key;
//this is for comparable in TreeMap
private int myCount;
private static int count;
public TreeKey (int key)
{
this.key=key;
count++;
myCount=count;
}
public TreeKey (){}
public int getKeyValue()
{
return key;
}
public int getCount()
{
return myCount;
}
public int compareTo(Object anotherKey) throws ClassCastException
{
int anotherCount = ((TreeKey )anotherKey).getCount();
return this.count - anotherCount;
}
}
gnosa at 2007-7-12 20:09:08 >

# 5
Thanks.
I am using TreeMap. I actually don't want the keys to get overwritten, so the keys in the Map is comparable according to the counter.
There is a class extends TreeMap. I need to use another getElement method sometimes.
public class MyTree extends TreeMap{
public MyTree () {
}
public Element getElement(int id, double rate)
{
Collection values=this.values();
Iterator iter=values.iterator();
while(iter.hasNext())
{
Element ele=( Element)iter.next();
if(ele.isMe(id, rate))
{
return ele;
}
}
return null;
}
public String toString()
{
String eleString="";
Collection values=this.values();
Iterator iter=values.iterator();
while(iter.hasNext())
{
Element ele=( Element)iter.next();
eleString += ele.toString()+ "\n";
}
return eleString;
}
}
gnosa at 2007-7-12 20:09:08 >

# 9
So two keys can never be equal? So you will never be able to retrieve an object if you lose its original key object?
And if this is 'not a real key actually' why this:
//this is for comparable in TreeMap
private int myCount;
because the only time TreeMap will use that is if it is the key.
and why did you say 'My Key class is like this' if that isn't the key.
I think you have confused yourself completely here.
First define your objective, then try it the simple way first, then refine.
ejpa at 2007-7-12 20:09:08 >
