daokia
daokia

Reputation: 1

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!

Upvotes: 0

Views: 600

Answers (3)

xs0
xs0

Reputation: 2897

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

Upvotes: 0

sjr
sjr

Reputation: 9875

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.

Upvotes: 2

Tom Anderson
Tom Anderson

Reputation: 47163

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.

Upvotes: 4

Related Questions