检索键值时Hashmap中的ArrayList

时间:2013-05-10 10:54:57

标签: arraylist hashmap

private static Map<String, ArrayList<String>> loadValues = new HashMap<String,ArrayList<String>>();
static ArrayList details = new ArrayList<String>();

我输入2组值...说..键:1个值:abc,c @ c.com,555和键:2个值:xyz,x @ z.com,765

我尝试过这个。

System.out.println("Enter the User ID:");
        userID = in.next();
        System.out.println("Enter your name:");
        name = in.next();
        details.add(name);
        System.out.println("Enter your e-mail:");
        email = in.next();
        details.add(email);
        System.out.println("Enter your contact number:");
        contactNo = in.next();
       details.add(contactNo);
        loadValues.put(userID, details);

并使用迭代器打印... 当我尝试打印时,它会打印出......

1: abc, c@c.com, 555 ,xyz,x@z.com,765
 2:  abc, c@c.com, 555 ,xyz,x@z.com,765

但是,我需要打印,1: abc, c@c.com, 555 and 2: xyz,x@z.com,765 我该怎么办?

1 个答案:

答案 0 :(得分:1)

这是因为您没有为两条记录创建新的List。由于细节是静态的,因此地图中的两个记录都指向同一个列表。

static List a = new ArrayList();
a.add(foo);
map.put(1, a);
a.add(bar);
map.put(2, a);
map.get(1) == map.get(2)
>> true

您需要执行以下操作:

List a = fillList();
List b = fillList();
map.put(1, a);
map.put(2, b);

其中fillList表示创建List的新实例并填充它。

相关问题