Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Java Hashtable performance for contains() method.

1 view
Skip to first unread message

zer0frequency

unread,
Jul 9, 2004, 3:27:37 PM7/9/04
to
Hi all,

I am working on a conversion code (from C++ to JAVA) - now in C++
there is a Rougwave Hashtable that can create hashtables with the
contains() or equals() method which does lookups based on values....

However in JAVA the hashtable looksup objects based on
Object-Reference, so the following lookup fails in java and works in
C,

(Hashtable containing an Object called MyObject with Key as a simple
object as Integer)

Java version:

Hashtable myHash = new Hashtable();

Integer i = new Integer(1);
Integer j = new Integer(1);
// i & j are same values but different objects in
memory

MyObject myObj = new MyObject();

MyObject tmpObj = null;

// Adding myObj into myHash
myHash.put(i, myObj);

// Now logically tmpObj should get the myObj ref.
tmpObj = myHash.get(j);

// But tmpObj will be null cuz i & j are different
objects...


Now to overcome this problem, I wrote my own methods, which get
Objects from hashtable based on the keyType - i.e. for the key as
Integer, I wrote hash.getUsingInt() - which extracts Enumeration from
the hash, and then compares the keys (Integer's values) to find the
match...

This works, but I am sure it makes the processing slow... (I think?)

Please help if you got any ideas to improve performance !!!!

Mark Thornton

unread,
Jul 9, 2004, 3:40:17 PM7/9/04
to
zer0frequency wrote:
> Hi all,
>
> I am working on a conversion code (from C++ to JAVA) - now in C++
> there is a Rougwave Hashtable that can create hashtables with the
> contains() or equals() method which does lookups based on values....
>
> However in JAVA the hashtable looksup objects based on
> Object-Reference, so the following lookup fails in java and works in
> C,

java.util.HashMap and java.util.Hashtable both use Object.equals to test
for equality. The class java.util.IdentityHashMap uses == (i.e.
reference equality).

> (Hashtable containing an Object called MyObject with Key as a simple
> object as Integer)
>
> Java version:
>
> Hashtable myHash = new Hashtable();
>
> Integer i = new Integer(1);
> Integer j = new Integer(1);
> // i & j are same values but different objects in
> memory
>
> MyObject myObj = new MyObject();
>
> MyObject tmpObj = null;
>
> // Adding myObj into myHash
> myHash.put(i, myObj);
>
> // Now logically tmpObj should get the myObj ref.
> tmpObj = myHash.get(j);
>
> // But tmpObj will be null cuz i & j are different
> objects...

Wrong. This code should retrieve the myObj value.

Mark Thornton

0 new messages