简体   繁体   English

2 个哈希表键

[英]2 Hashtable Keys

i'm having 2 records that is a title.我有 2 条记录是标题。

Example例子
Record 1: My Title记录 1:我的头衔
Record 2: My Another Title记录 2:我的另一个标题

I need to store them into an ArrayList using Hashtable.我需要使用 Hashtable 将它们存储到 ArrayList 中。

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 arraylist it only shows me the 2nd record.当我通过遍历 arraylist 打印我的项目结果时,它只显示第二条记录。

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. 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; class 的实现无需在变量的类型中描述; 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.您将对同一个哈希表的引用放入finalArray两次。 When you change the hashtable, you will see the changes affect both elements of finalArray .当您更改哈希表时,您将看到更改会影响finalArray的两个元素。

You're inserting the same Hashtable for both records.您正在为两条记录插入相同的 Hashtable。 As you're inserting the second record, you override the values for the first, so you get the second twice..当您插入第二条记录时,您会覆盖第一条记录的值,因此您会两次获得第二条记录。

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

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