Re: Encapsulating HashMap bulding
On 5/10/2010 3:20 PM, Roedy Green 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.
public class Table<R> {
private final List<UniqueIndex<?, R>> indexes =
new ArrayList<UniqueIndex<?, R>>();
public <K> UniqueIndex<K, R> addIndex(KeyExtractor<K, R> extractor) {
// create index and add to indexes
}
public void add(R item) {
for(UniqueIndex<?, R> index: indexes) {
index.add(item);
}
}
}
public class UniqueIndex<K, R> {
private final KeyExtractor<K, R> extractor;
private final Map<K, R> map = new HashMap<K, R>();
public R add(R item) {
return map.put(extractor.extract(item), item);
}
public Map<K, R> getMap() { /* return copy */ }
}
public interface KeyExtractor<K, R> {
K extract(R);
}
> Perhaps you could do it with reflection.
Don't use reflection unless you have a really good reason. I would
prefer to use code generation before I use reflection in this situation.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>