Addison Addison - 6 months ago 19
Java Question

Is it possible to create a Map where every Key points to the same Value?

Is it possible (In Java) to create a Map where, no matter what key I was to search for, I would retrieve the same value? We can assume either a finite or infinite amount of keys.

I considered a map of size 1 and load factor of 1.0, with that value stored in it, but I'm nearly positive that the hashmap implementation will recognize the collision, and return null anyway.

I also entertained the possibility that if I created my own hashfunction for a variable, or even a new datatype that implemented Map, that I should be able to do this, but it may be a little messy. Perhaps not?

Of course, simply mapping the value to every single key would be very inefficient (unless there is a built in method for this, that I overlooked), and nowhere near as entertaining as hearing SO's answers.

Answer

I suppose the most reasonable way to do this with existing API is like the following:

// Java 6/7
new TreeMap<K, V>(new Comparator<K>() {
    @Override
    public int compare(K lhs, K rhs) {
        return 0;
    }
});

// Java 8+
new TreeMap<K, V>((a, b) -> 0);

This TreeMap considers all keys equal but will otherwise maintain pretty good Map semantics.

Note that the first key you put in the Map will stay in it forever unless you remove it.

i.e.

m.put("abc", "123");
m.put("def", "456");
// prints something like {abc=456}
System.out.println(m);

So you might keep that in mind for example if you planned on examining the entrySet.

Comments