简体   繁体   中英

2 Hashtable Keys

i'm having 2 records that is a title.

Example
Record 1: My Title
Record 2: My Another Title

I 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 arraylist 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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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