Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap<String, ArrayList<String>>

Tags:

java

hashmap

I am trying to get HashMap store a String and a ArrayList<String>. Basicly what I want is for the first String to be a Name, and the arraylist to contain every country the user have been to.

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

The problem I meet is whenever the user puts in a country, the country will be stored under both names:

"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.");
    }

Does someone knows why the HashMap is not storing the key/values the way I want too?

like image 849
Hablo Avatar asked Mar 05 '26 08:03

Hablo


1 Answers

Your code is nota completed so I can't know what is test an thearchive. But let's create an example:

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

I hope it helps.

like image 70
augustoccesar Avatar answered Mar 06 '26 22:03

augustoccesar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!