Re: typesafe java.util.Map construction and initialization
 
Josef Svitak wrote:
If I have:
public class foo {
  private interface BarIF { }
  private class BarImplOne implements BarIF { public BarImplOne() {} }
  private class BarImplTwo implements BarIF { public BarImplTwo() {} }
  private java.lang.String keys[] = { "key1", "key2" };
  private final bars[] = { new BarImplOne(), new BarImplTwo() };
  private final java.util.Map<String, BarIF> theMap;
  public foo() {
    // Can I do this... (doesn't work)
    theMap = new java.util.HashMap( keys, bars );
    // instead of this? (works)
    theMap.add( "key1", new BarImplOne() );
}
javac complains of not having a ctor for HashMap(String[], BarIF[]).
Yes, you can see that from the API docs.
You should be able to do is something like:
public class Foo {
     private interface Bar { }
     private class BarImplOne implements Bar { public BarImplOne() {} }
     private class BarImplTwo implements Bar { public BarImplTwo() {} }
     private final java.lang.String[] keys;
     private final Bar[] bars;
     private final java.util.Map<String, Bar> map;
     public Foo() {
         map = new java.util.LinkedHashMap<String, Bar>();
         map.put("key1", new BarImplOne());
         map.put("key2", new BarImplTwo());
         int num = map.size();
         keys = new String[num];
         map.keySet().toArray(keys);
         bars = new Bar[num];
         map.values().toArray(bars);
     }
     public static void main(String[] args) {
         Foo foo = new Foo();
         System.out.println(foo.map);
         System.out.println(java.util.Arrays.asList(foo.keys));
         System.out.println(java.util.Arrays.asList(foo.bars));
     }
}
Or you can write your own method to construct a map from two arrays
(which I wouldn't really recommend).
Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/