Board index » jbuilder » Java Map Classes for C++ developer

Java Map Classes for C++ developer


2004-06-30 04:35:50 AM
jbuilder2
In C++, I would use STL to map in integer to an object pointer, e.g.,
// define the type
typedef std::map<int,MyClass*>INT2MYCLASS;
// instantiate the class
INT2MYCLASS m_map;
// add a map entry
m_map[123] = p1;
// read back the map entry
MyClass* p2 = m_map[123];
// check pointers are equal
assert(p1 == p2);
In Java, I could use a HashMap, which maps objects to objects. The problem
I have is that an "int" is not an object. So I tried using "new Integer(x)"
to turn the int into an object, but I don't know that this is correct and I
think that the Object.hashCode() will not be the same for the two "new
Integer(123)" objects:
HashMap m_map = new HashMap();
m_map.put(new Integer(123), p1);
MyClass p2 = m_map.get(new Integer(123));
So, what is the recommended way to map a scaler value (e.g. PlayerID) to an
object, e.g. the Player object?
Thanks...
 
 

Re:Java Map Classes for C++ developer

Bryan wrote:
Quote
In Java, I could use a HashMap, which maps objects to objects.
A TreeMap is more similar to the STL map class, but depending on what
you really need, a HashMap might be equally or more appropriate.
Quote
The problem
I have is that an "int" is not an object. So I tried using "new Integer(x)"
to turn the int into an object, but I don't know that this is correct
It is.
Quote
and I
think that the Object.hashCode() will not be the same for the two "new
Integer(123)" objects:
It will be the same. In fact, the javadoc for the Integer class says,
"Returns: a hash code value for this object, equal to the primitive int
value represented by this Integer object."
Quote
HashMap m_map = new HashMap();
m_map.put(new Integer(123), p1);
MyClass p2 = m_map.get(new Integer(123));

So, what is the recommended way to map a scaler value (e.g. PlayerID) to an
object, e.g. the Player object?
Exactly the way you did it, though you left out a cast. The get method
returns an Object which will need to be cast to a MyClass. Two new
features in JDK 1.5 will eventually (soon) make this easier. Your
example code would change to:
HashMap<Integer, MyClass>m_map = new HashMap<Integer, MyClass>();
m_map.put(123, p1);
MyClass p2 = m_map.get(123);
You can see that the type of the map is specified using a syntax similar
to C++ templates (though the implementation is very different; Java has
"Generics" not templates) and that 123 is automatically converted to an
Integer. Also, since the type of the HashMap has been given, the cast
to MyClass is not needed.
--
Gillmer J. Derge [TeamB]