Question

this is my issue. Im storing Data into a database table which has a column where i store the hashcode (or can be some other Unique String such as an ID because the JVM can re-locate the objects, changing the hashcode). But once i get that String i want to access to the object mapped to that String. I can do it with HashMap like:

ConcurrentHashMap<String, MyClass> MyClassDictionary;

The average of objects to store would be like +800. I can take other options to avoid this kind of things but i really want to know if some of you know a better way than using HashMap.

I found something about a Referenceable Interface that i could implement, you can check it out in the next link: http://docs.oracle.com/javase/jndi/tutorial/objects/storing/reference.html

Thanks for reading.

Was it helpful?

Solution

You can use any key in the HashMap which is Immutable. String by nature is immutable, which means the object cannot be changed, if someone tries to change the object, a new one will be created and the original remains as it is. So you are safe if you are using unique strings as key. The advantage of using immutable keys in any hashed collection is that, your key object will always be preserved or unchanged. And there will be no chance that someone by mistake and change the key, and leading to a problem that you lose the reference to the value. If the key is not immutable and it is changed from some other place in the code. Then you will never be able to fetch the associated value to that key. This is sometimes refer to as memory leak in java.

OTHER TIPS

The hashCode of an object is very explicitly not unique; it is quite legal for your hashCode() method to just return 0 all the time. You will need to use some other identifier.

You look like you're crossing two separate issues here: Are your objects being stored in the database or just in memory? If they're only in memory, then there's no reason to put the identifier in the database, because the objects will get thrown away when the program restarts. If they're in the database, you need some sort of object-relational mapping solution to recreate Java objects from database rows, and you should look at JPA.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top