tags:

views:

842

answers:

3

hi
how to store multiple arraylist objects in hashtable in java & how do i get it back.

A: 

Don't. Use HashMap instead of Hashtable - it's not synchronized.

Map<String, ArrayList<SomeObject>> myMap = new HashMap<String, ArrayList<SomeObject>>();
ArrayList<SomeObject> list = new ArrayList<SomeObject>();
list.add(someObjectInstance1);
list.add(someObjectInstance2);
myMap.put("key1", list); // stores list containing instances #1 and #2 under key "key1"
ArrayList<SomeObject> list2 = new ArrayList<SomeObject>();
list2.add(someObjectInstance3);
myMap.put("key2", list2); // stores list2 containing instance #3 under key "key2"

SomeObject obj1 = myMap.get("key1").get(0); // returns instance #1
SomeObject obj2 = myMap.get("key1").get(1); // returns instance #2
SomeObject obj3 = myMap.get("key2").get(0); // returns instance #3

All that said, you may want to consider using Multimap from Google Collections instead:

Multimap<String, ArrayList<SomeObject>> myMap = ArrayListMultimaps.create();
myMap.put("key1", someObjectInstance1);
myMap.put("key1", someObjectInstance2);
myMap.put("key2", someObjectInstance3);

SomeObject obj1 = myMap.get("key1").get(0); // returns instance #1
SomeObject obj2 = myMap.get("key1").get(1); // returns instance #2
SomeObject obj3 = myMap.get("key2").get(0); // returns instance #2

You can see how much more straightforward this approach is.

ChssPly76
The code above does not add <b>multiple</b> arraylist objects in a <b>Hashtable</b>
Murali VP
I would think that it'd be pretty obvious how to add a 2nd (3rd, Nth) list to the map by looking at the above code but apparently I was wrong. Updated to illustrate two lists.
ChssPly76
There I reverted my downvote, hope you feel better.
Murali VP
A: 

Use the Hashcode of each Linklist as the Key. Using a FOR Value mentioned in one of the posts as the Keys is probably not a good idea. What if you have to add a new List somewhere else ? You will have to traverse the entire map to find the next greatest key.

Geek
using the hashcode of the linked list as a hash key is a horrible idea. First of all, it has no meaning to the application. The only reason for putting things into a hashtable (as opposed to a list for example) is to be able to look them up by key. Second, there are lots of collisions: If you put in three empty lists, they would override eachother. Third, you should never use a hash key that can change, and the hashcode of a list changes as the list contents change.
Thilo
Thilo, Your answer is very good. My mistake, I assumed that the Hashcode will be equal to the address in the memory where the List is stored and hence Unique.
Geek
A: 

Hi, I have another doubt.

I have made the hashMap along with the arrayList. Is there some way to get back the complete arrayList from the hashmap corresponding to a particular key. I need to update the arrayList and add it to the hashMap once again.

Thank You

Shailendra