簡體   English   中英

HashMap中 <String, ArrayList<String> &gt;

[英]HashMap<String, ArrayList<String>>

我試圖讓HashMap存儲一個字符串和一個ArrayList<String>. 基本上我想要的是第一個String為Name,而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不按我想要的方式存儲鍵/值嗎?

通常,您的問題是由於對所有人重復使用了相同的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.");
    }

您的代碼尚未完成,所以我不知道測試歸檔文件是什么。 但讓我們創建一個示例:

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);

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM