I have three Hash Table like that,
HashTable ht1 = { (1, 100), (2, 200) }
HashTable ht2 = { (1, 100), (2, 200) }
HashTable value = { (100, null), (200, null) }
Is it possible in Java to store a pointer in ht1 and ht2 instead of 100 and 200, which points (and can access) to 100 and 200 of value hashtable. Example, I want structure like ht1 = { (1, pointer1), (2, pointer2) } where pointer1 —-) 100 (which is stored on value hashtable) Can anybody help me how can this be possible ? I am using Java inbuilt Hashtable construct. Thanks.
A couple of comments.
Hashtableis useful when you need to have synchronized access to the elements in aMap, if that’s not the caseHashMapis preferred.In Java we don’t have “pointers”, but surely we have references to objects (please remember that in Java all objects are passed by value, not by reference). And yes, you can store references to objects as values in a
Map. I think you’re confusing concepts from C/C++ with concepts in Java, maybe you should explain exactly what do you want to do with the “pointers”.Just to be sure – you can have a
Mapsuch as this one in Java:In the above code, the keys and values of the
Mapare references toIntegerobjects, and theIntegerclass is immutable, meaning that you can’t change its value once it’s in place – but of course, you can change the value pointed to by a key in theMap.EDIT :
The sample in the question would look like this in Java:
In the above code all the integers in the three maps are references to immutable objects: what appears to be the number 100 in reality is a reference to the object
new Integer(100), and becauseIntegeris an immutable class, it’s possible that all three references tonew Integer(100)point to exactly the same object in memory.So, answering your question: yes it’s possible in Java to store a pointer in ht1 and ht2 instead of 100 and 200, which points (and can access) to 100 and 200 of value hashtable. In fact that’s what is happening already, and there’s no other way to do it – because maps in Java can not store primitive types (like
int), only references. And again, given that all instances ofIntegerare immutable, you can not change their value, because doing so would change the values in the other places where they’re being shared and used.