How to define Hashtable values, when the hashtable automatically grows?
I have two hashtables in my code:
Hashtable<String, Vector><SellerData>> productList
Hashtable<String, Vector><String>> sellerList
These hashtables are member variables of a class and they are defined in the constructor of that class. Also in the same constructor, there are loops that allocate memory for the vectors in these hashtables. However, the capacity of Java hashtables are automatically increased as more elements are inserted, I'm wondering how I can make sure Vectors in these newly added hashtable slots are also defined and have memory allocated for them?
My current solution is that the user code does some checking to make sure vectors in above hashtables are defined, but I was wondering if there is some other way I could do this so the user code does not have to do any checking?
Thanks,
P.
[884 byte] By [
PaperCuta] at [2007-10-2 5:41:54]

Sorry, I mistyped the hashtable declarations, the correct form is:Hashtable<String, Vector><SellerData>> productListHashtable<String, Vector><String>> sellerListP.
Sorry, I mistyped the hashtable declarations, the correct form is:Hashtable<String, Vector><SellerData>> productListHashtable<String, Vector><String>> sellerListP.
> Could you explain why it's better to use HashMap
> instead of Hashtable and ArralyList instead of
> Vector?
>
Vector and Hashtable were around before the Collections Framework. They were retrofitted into it after the fact, but they're just kept around for legacy reasons. They're also synchronized, which you don't normally need.
ArrayList and HashMap were created as part of the Collecitons Framework from day one, so they don't have extraneous, non-standard methods, and they're not synchronized.
A few notes:
1) Even though you assign a value to an attribute in the constructor, do NOT assume it will be assigned a value in your methods. Polymorphism will bite your behind on this one. Say you have the following class setup:class A {
Integer a;
public A() { X(); }
public X() { // init code }
}
class B extends A {
public B() { super(); a = new Integer(0); }
public X() { System.err.println( a.toString() ); }
}
This will cause an exception since the constructor for B calls the constructor for A which calls B.X BEFORE you set a. Can't tell you how difficult it was to track this one down the first time it happened to me.
But to your question! It is impossible unless you implement an extension for Hashtable as follows
class MyHash extends Hashtable {
// setup as a Hashtable<String, Vector> in constructor.
public get(Object key) {
Object ret = super.get( key );
if ( ret = null )
return new Vector();
else
return ret;
}
// similar code for entrySet() and values()
// if you need non-null values for these methods too.