我有两张唱片,这是个标题。
示例
唱片1:我的头衔
唱片2:我的另一个标题
我需要使用Hashtable将它们存储到ArrayList中。
我就是这么做的。
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);
}
}当我通过遍历数组列表来打印我的项目结果时,它只显示了第二次记录。
有什么建议可以让它显示这两张唱片吗?
谢谢!
发布于 2011-04-30 17:51:50
在创建第一和第二记录之间,放置:
this.items = new Hashtable <String, String>();问题是,对于两个记录,您都重复使用相同的哈希表。
此外,现在您应该使用HashMap而不是Hashtable,您应该以最广泛的有用类型声明变量,这里的意思是列表而不是ArrayList,映射而不是哈希表或HashMap。不需要在变量的类型中描述实现类;在使用变量时不需要知道它的细节,所以它只是杂乱无章。
发布于 2011-04-30 17:53:12
您要两次在finalArray中引用相同的哈希表。当您更改哈希表时,您将看到这些更改会影响finalArray的两个元素。
发布于 2011-04-30 17:53:31
您正在为两个记录插入相同的Hashtable。当您插入第二条记录时,重写第一条记录的值,因此第二条记录将覆盖第二条记录。
https://stackoverflow.com/questions/5843555
复制相似问题