Java map based on object reference?
So, I'd like to use a java map where the keys are an object..开发者_Python百科.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.
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.
You should have a look at IdentityHashMap.
This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values).
Check out Guava's Multimaps (implementations listed on the Multimap
interface page).
You are searching for a multi-map. Java Collection Framework doesn't give you this. But you can mimic it associating a LinkedList
(eventually with a single element) to every key. It's very easy.
Just for completness: Guava
's MapMaker
makes maps with identity equivalence as a default for weak and soft keys. Look at code here
精彩评论