Hash tables with list or Vectors
Hi All,
I would like to create a hash table that holds many values for one key, for this we might have to use stuff like lists along with hash tables(please let me know if there is any other better alternative for this!). It'll be great if someone has a very simple example of how to add elements and retrive many elements that belongs to a key. It'll be great if someone can give a couple of lines code illustrating how to do this.
Thanks
Try this...................
Use HashMap and ArrayList instead of HashTable and Vector respectively for better perofmance, if you are sure that this information will not be modified concurrently.
Here is simple example describing the usage of HashMap and ArrayList.
Let us say you have three languages Java,C and Java Script.
The follwoing books are available for each language.
Java - Core Java, Complete Reference, Java Bible
C - Let us C, Programming with C
Java Script - Java Scritp:The definitive guide, Java script Bible
You have to store books of each language as a collection and you want retrieve all the books of particluar language by passing a key. Here the key is the language itself.
//Declare the variables
HashMap langMap = new HashMap();
ArrayList javaList = new ArrayList();
ArrayList cList = new ArrayList();
//Add the books to individual lists
ArrayList javaScriptList = new ArrayList();
javaList.add("Core Java");
javaList.add("Complete Reference");
javaList.add("Java Bible");
cList .add("Let us C");
cList .add("Programming with C");
javaScriptList .add("Java Scritp:The definitive guide");
javaScriptList .add("Java script Bible");
//Now add the lists to HashMap with language name as key
langMap.put("java",javaList);
langMap.put("c",cList);
langMap.put("javascript",javaScriptList);
//Now if want to retireve a specific list, then pass the key and retrieve the list
cList = langMap.gut("c");
//If u want to access inside the elements of the list
cList.get(0);//Returns "Let us C"
cList.get(1);//Returns "Programming with C"