2

I would like to know if is it possible to create a vector of hashtables ?

i tried

java.util.Hashtable<String, String>[] info = new java.util.Hashtable<String, String>();

but haven't any luck :(

Thanks.

Mat
  • 202,337
  • 40
  • 393
  • 406
Winter
  • 1,896
  • 4
  • 32
  • 41

4 Answers4

4

I think you want

ArrayList<Hashtable<String, String>> info = new ArrayList<Hashtable<String, String>>();
Bala R
  • 107,317
  • 23
  • 199
  • 210
4

A Vector is a List, and a Hashtable is a Map, so what you want is a List of Maps.

I'd advise you to use ArrayList instead of Vector and HashMap instead of Hashtable, respectively (as discussed here and in many other questions), but most of all I'd advise you to change your requirements.

In most cases, you'd want a Map of Lists rather than a List of Maps, and if you do, I'd use one of the many custom implementations available, first and foremost Guava's Multimap.

Community
  • 1
  • 1
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
3

You probably want:

ArrayList<Hashtable<String, String>> info =
    new ArrayList<Hashtable<String, String>>();

This can be simplified somewhat with type inference and a library such as Guava:

ArrayList<Hashtable<String, String>> info = Lists.newArrayList();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Try to make sure you are using as abstract an interface for the collections you are using as possible.

List<Map<String, String>> info= new ArrayList<Map<String, String>>();

Then you can add your hashtables

Map<String, String> infoElement= null;
for( something in someOtherThing ) {
    infoElement= new Hashtable<String, String>();
    // add your logic
    info.add(infoElement);
}
Dave G
  • 9,639
  • 36
  • 41
  • i still have a problem. i have this infoElement in a for cycle and everytime i update the infoElement all info elements assumes the new infoElement value because the info.add method only set a pointer to infoElement... – Winter May 19 '11 at 22:02
  • @Winter - Ok So what you need to do is create a new HashTable for the next "infoElement" you want to add and update that. Collections inside collections can get very tricky if you're not sure which contained collection you are working with. I've done a lot of work under Perl with Hashes of Hashes ... trust me it gets really interesting remembering which depth you're at. – Dave G May 19 '11 at 23:45
  • @Winter, I've added a small correction indicating how to handle this in a loop situation. hope it helps. – Dave G May 20 '11 at 02:04