Reputation: 31
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?
Upvotes: 3
Views: 11140
Reputation: 285430
Usually your problem is due to re-using the same ArrayList for all people, so that all folks share the same Countries, all held by the one single ArrayList. A solution is to create a new ArrayList for each person -- meaning new ArrayList<String>
needs to be inside some loop where you create your traveler's name String.
So for example, you could change your code to this:
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.");
}
Upvotes: 1
Reputation: 666
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.
Upvotes: 1