Re: Encapsulating HashMap bulding
On May 11, 8:08 am, Kevin McMurtrie <mcmurt...@pixelmemory.us> wrote:
In article <qf1hu5d02ptja2duic3saa60qgolal9...@4ax.com>,
Roedy Green <see_webs...@mindprod.com.invalid> wrote:
Can anyone think of a way to write a method that takes an array of X,
and produces a HashMap<Key,X>
How would you specify the name of the key field/method?
Maybe you could do it by making X implement an interface that defines
the key.
Perhaps you could do it with reflection.
If the key is easily derived from the value, what you might have is a
set rather than a map. If that's not the case, Generics trickery will
make it a simple task.
Good point. Although I believe that could not be stated for the most
general case.
interface Key
{
boolean equals(Object other);
int hashCode ();
// Other stuff
}
interface Keyed
{
Key getKey();
}
public <K extends Keyed> HashMap <Key, K> keyedMap (K[] in)
{
HashMap<Key, K> map= new HashMap<Key, K>(in.length);
for (K keyed : in)
map.put(keyed.getKey(), keyed);
return map;
}
You could even put generics on they Key to support different categories
of keys. It would be nearing the boundary of where Generics stops
making coding easier, though.
Roedy did not state how exactly the key is obtained for a particular
value although he seems to insinuate that it's a property of the
value. I prefer a more modular approach where the key finding
algorithm is completely decoupled from the value type. This is much
more modular and allows for better reuse. Here are some advantages:
- If you have multiple key candidates making the value type implement
a particular interface limits you to using exactly one of those
candidates. Or you have to wrap values in another type which
implements the key extraction interface which has all sorts of nasty
effects because object identity changes - and it might also be slower,
since more objects are needed.
- You can obtain keys for items which do not exhibit matching
properties at all.
- You can even create a completely new key object based on arbitrary
state which can be extracted from the value object or from somewhere
else (e.g. a counter).
Note also how I have separated Map creation from Map filling in order
to retain even greater modularity of the code. That way you can apply
the key extraction and map filling algorithm to even more Map types
than only HashMap. You can even fill a single map from multiple value
sources.
Kind regards
robert