Hi,
The problem I have is about passing one Collection object into another, such as passing a Vector object into a Hashmap. I've tried to do this in the two files included below: VectorToHash.java and VectorToHashTest.java.
The problem specification is: I put values into a Vector object and then passed it to a Hashmap and then I want to retieve those values out. I also want to associate each Vector object passed to the Hashmap with a Key object. I've made an attempt to do this below in the two .java files mensioned, but I'm stuck. Although the code does compile, I need help to correct it to work as specified. Could you help me correct my code, and help me understand what problem situations would require a Vector object to be passed to a Hashmap?
Many Thanks,
Mark Yadav.
VectorToHash.java
// VectorToHash.java - the purpose of theis class is to create methods
// that allow a Vector containing Strings to be added to a HashMap.
// The
Test program: VectorToHashTest then returns the vector from
// the HashMap and then extracts the values from the vector.
import java.util.*;
public class VectorToHash {
// HashMap to store vector
HashMap book = new HashMap();
Vector v = new Vector();
String[]
fruit = {"apple","banana","orange","tomato","pear"};
Integer[] id = new Integer[5];
// Method to add fruit to vector.
// A vector is then returned
public Vector addFruit(Vector v){
for(int i = 0; i < fruit.length; i++)
v.add(fruit[i]);
return v;
}
// method to add vector to HashMap. The retuned Vector
// from the previous method is added to the HashMap
public void addVector(Vector v, HashMap m){
for(int i = 0; i < 5; i++)
m.put(id[i], v);
}
}
VectorToHashTest.java
// VectorToHashTest.java Tests the VectorToHash class
import java.util.*;
class VectorToHashTest{
public static void main(String[] args){
// Vector object
Vector b = new Vector();
Vector c = new Vector();
// HashMap object
HashMap hp = new HashMap();
//
VectorToHash vth = new VectorToHash();
c = vth.addFruit(b);
// add vector to HashMap
vth.addVector(c,hp);
//output contents of HashMap
Set keys = hp.keySet();
Iterator keyIter = keys.iterator();
while(keyIter.hasNext())
System.out.println((Integer)keyIter.next());
}
}
