Re: How to create array of hash table with correct types
Roedy Green wrote:
On Thu, 3 Jul 2008 16:38:21 -0700 (PDT), jonbbbb <jon.berg@gmail.com>
wrote, quoted or indirectly quoted someone who said :
I tried the following, which does not compile:
private Hashtable<String, NodeAddress>[] cache = {new
Hashtable<String, NodeAddress>(),new Hashtable<String,
NodeAddress>()};
How about actually *citing* the error message?
~/projects/testit/src/testit/Foo.java:22: generic array creation
I guess that means you can't create a generic array.
Could that be? Could the error message actually have already answered your
question?
Let's research:
<http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.3>
It is a compile-time error if the element type is not a reifiable type (?4.7)
<http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.7>
A type is reifiable if and only if one of the following holds:
* It refers to a non-generic type declaration.
* It is a parameterized type in which all type arguments are
unbounded wildcards (?4.5.1).
* It is a raw type (?4.8).
* It is a primitive type (?4.2).
* It is an array type (?10.1) whose component type is reifiable.
So the answer is, no, you cannot do that.
Anyway, arrays and generics don't play well together. Make a List of Maps
instead.
Additionally, I suggest using HashMap instead of Hashtable, and declaring the
variable in terms of List <Map> rather than a concrete type.
private List <Map <String, Foo>> cache
= new ArrayList <Map <String, Foo>> ();
{
cache.add( new HashMap <String, Foo> ());
cache.add( new HashMap <String, Foo> ());
}
--
Lew