Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java map based on object reference?

Tags:

java

So, I'd like to use a java map where the keys are an object...but rather than keying on the object's value, they key on the object ID. So, something like the following would be totally valid code:

Map<String, Integer> map = new HashMap<String, Integer>();

String s1 = "hi!";
String s2 = "hi!";

map.put(s1, 10);
map.put(s2, 47);

Is this possible? Is there a simple way to do this without building an object ID or something overly cumbersome in my class? Basically, I need a way to associate an ever-changing list of values with a given object. This list of values will potentially be different for objects that have the same value, hence why the default map doesn't work. Other than refactoring my class to do this myself (not really an option, given the time) is there anything that I could use?

Thanks.

EDIT: Further information.

The example above was just an example. What I will be using this for is the implementation of a Uniform-Cost search algorithm. For any given node in a search with this algorithm, one must also have the path that has been taken so far. The reason a value-based hash map doesn't work is that this algorithm can reiterate over already-explored nodes. The paths would be different at this point, although the value of "where am I now?" is identical.

like image 287
rybosome Avatar asked Apr 26 '11 22:04

rybosome


People also ask

Is Java map by reference?

Java is pass-byvalue only. No where it is pass-by-reference. inputMap and valueMap (copy of inputMap) are both references to the same hashmap.

Does HashMap store reference or object?

Description. A HashMap stores a collection of objects, each referenced by a key. This is similar to an Array, only instead of accessing elements with a numeric index, a String is used.

What does keySet return in Java?

keySet() method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them. Parameters: The method does not take any parameter.

Does a HashMap get return a reference?

It returns a reference. You can pretty much assume this is the case unless otherwise specified.


1 Answers

I think IdentityHashMap will do the trick. However, both strings will point to the very same instance since you used a string literal. Try s1 = new String("hi!") and s2 = new String("hi!") together with an IdentityHashMap instead.

like image 147
Sebastian Zarnekow Avatar answered Oct 21 '22 15:10

Sebastian Zarnekow