i'm having 2 records that is a title.
Example
Record 1: My Title Record 2: My Another TitleI need to store them into an ArrayList using Hashtable.
This is what i do.package com.Testing;
import java.util.Hashtable;
import java.util.ArrayList;
import java.util.Dictionary;
public class AnotherClass {
private Hashtable <String, String> items = new Hashtable <String, String>();
private ArrayList <Hashtable <String, String>> finalArray = new ArrayList <Hashtable <String, String>>();
public ArrayList <Hashtable <String, String>> returnArray() {
return finalArray;
}
public void adding() {
this.items.put("Record", "Record 1");
this.items.put("Format", "My Title");
this.finalArray.add(items);
this.items.put("Record", "Record 2");
this.items.put("Format", "My ANOTHER Title");
this.finalArray.add(items);
}
}
When i do a print of my result of items by traversing the arrayl开发者_StackOverflow社区ist it only shows me the 2nd record.
any advice in getting it to show both records?
thanks!
In between the creation of the first and second records, put:
this.items = new Hashtable <String, String>();
The problem is that you're reusing the same hashtable for both records.
Also, you should use HashMap instead of Hashtable these days, and you should declare variables with the broadest useful type, which here means List rather than ArrayList, and Map rather than Hashtable or HashMap. There is no need to describe the implementation class in the variable's type; it's a detail you don't need to know when using the variable, so it's just clutter.
You're putting a reference to the same hashtable into finalArray
twice. When you change the hashtable, you will see the changes affect both elements of finalArray
.
You're inserting the same Hashtable for both records. As you're inserting the second record, you override the values for the first, so you get the second twice..
精彩评论