繁体   English   中英

2 个哈希表键

[英]2 Hashtable Keys

我有 2 条记录是标题。

例子
记录 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);
    }
}

当我通过遍历 arraylist 打印我的项目结果时,它只显示第二条记录。

让它显示两个记录有什么建议吗?

谢谢!

在创建第一条和第二条记录之间,放置:

this.items = new Hashtable <String, String>();

问题是您对两条记录重复使用相同的哈希表。

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. class 的实现无需在变量的类型中描述; 这是一个你在使用变量时不需要知道的细节,所以它只是杂乱无章。

您将对同一个哈希表的引用放入finalArray两次。 当您更改哈希表时,您将看到更改会影响finalArray的两个元素。

您正在为两条记录插入相同的 Hashtable。 当您插入第二条记录时,您会覆盖第一条记录的值,因此您会两次获得第二条记录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM