Please advise.. In the following code(Tested. Will work fine)
public class Exp_Test {
public static void main (String[] args) {
ArrayList<Hashtable> objArrlistHshTbl = new ArrayList<Hashtable>();
Hashtable objHashTable = new Hashtable();
objHashTable.put("Key1", "Value1");
objHashTable.put("Key2", "Value2");
objArrlistHshTbl.add(objHashTable);
objHashTable.clear();
objHashTable.put("Key3", "Value3");
objHashTable.put("Key4", "Value4");
objArrlistHshTbl.add(objHashTable);
System.out.println("Hi");//put a breakpoint here to check the values
}
}
I am expecting to see an arraylist with to Hashtables saved as array elements, first one with keys 'Key1' and 'Key2', Second one with Keys 'Key3' and 'Key4'. I get an array list with two hash tables, but values and keys inside hash table are coming as 'Key3' and 'key4' for both tables. Could someone explain. If it is a reference problem, how do I get two hash tables in to different array elements withouot creating multiple hash tables(I have to run the code inside a for loop to add multiple hash tables.Creating separate hash tables every time does not sound good)