HashMap <string,arraylist <string =“”>&gt; </string,>

时间:2014-11-14 00:42:22

标签: java hashmap

我试图让HashMap存储一个字符串和一个ArrayList<String>. 基本上我想要的是第一个String是一个名字,而arraylist包含用户去过的每个国家。

Example:
{Andrew, [USA, China]}
{Lola, [Sweden, Denmark]}

我遇到的问题是,只要用户进入某个国家/地区,该国家/地区就会以两个名称存储:

"The HashMap contains: {Andrew=[USA, China, Sweden, Denmark], Lola=[USA, China, Sweden, Denmark]}"

ArrayList<String> namelist = new ArrayList<>();
ArrayList<String> test = new ArrayList<>();
ArrayList<String> archive = new ArrayList<>();
HashMap<String, ArrayList<String>> thearchive = new HashMap<>();

(input.equals("New Country")){
    System.out.println("Name of the Person? ");
    String name = in.nextLine();
    if(namelist.contains(name)){
        System.out.println("Which Country have you visited?");
        String country = in.nextLine();
        if (archive.contains(country)){
            System.out.println("You've already visited this country.");
        }
        else {
            test.add(country);
            thearchive.put(name, country);
            System.out.println("HashMap Contains: " + thearchive);
        }
    }
    else{
        System.out.println("The person does not exist please add first.");
    }

有人知道为什么HashMap没有以我想要的方式存储键/值吗?

2 个答案:

答案 0 :(得分:1)

通常你的问题是由于为所有人重复使用相同的ArrayList,所以所有人共享相同的国家,全部由一个ArrayList保存。一个解决方案是为每个人创建一个新的ArrayList - 意味着new ArrayList<String>需要在你创建旅行者名字String的某个循环中。

例如,您可以将代码更改为:

ArrayList<String> namelist = new ArrayList<>();
ArrayList<String> test = new ArrayList<>();

// ArrayList<String> archive = new ArrayList<>();

HashMap<String, ArrayList<String>> arkivet = new HashMap<>();

(input.equals("New Country")){
    System.out.println("Name of the Person? ");
    String name = in.nextLine();

    archive = ArrayList<String>(); // **********
    arkivet.put(name, archive);  // ************

    if(namelist.contains(name)){
        System.out.println("Which Country have you visited?");
        String country = in.nextLine();
        if (archive.contains(country)){
            System.out.println("You've already visited this country.");
        }
        else {
            test.add(country);
            thearchive.put(name, country);
            System.out.println("HashMap Contains: " + thearchive);
        }
    }
    else{
        System.out.println("The person does not exist please add first.");
    }

答案 1 :(得分:0)

您的代码尚未完成,因此我无法知道什么是测试原型。但是,让我们创建一个例子:

HashMap<String, ArrayList<String>> list = new HashMap<String, ArrayList<String>>();
ArrayList<String> anotherlist = new ArrayList<String>();
anotherlist.add("Brazil");
anotherlist.add("USA");
list.put("Augusto", anotherlist);

我希望它有所帮助。