简体   繁体   中英

How can I print out a list of the keys in a hashmap?

I am storing objects in a hashmap and want to be able to see what I have in the hashmap. That is, If I want to view or change one of my objects, I want to print out a list of the keys so that I can see the choices available to me.

Here is how I put the keys into a printable format.

List<String> keys = new ArrayList<String>(allDogs.keySet());

That is at the beginning of my code. I would then declare some objects in this way.

System.out.println("\nWhat is the customer's name?");
custName = in.nextLine();

System.out.println("What is the dog's name");
name  = in.nextLine();

System.out.println("What is the dog's breed?");
breed  = in.nextLine();

System.out.println("What is the dog's age?");
age  = in.nextInt();
in.nextLine();

System.out.println("Does the dog have a valid rabies vaccine (Y/N)?");
vaccinated=false;
String invax = in.nextLine();
if (invax.toUpperCase().substring(0, 1).equals("Y")) 
    vaccinated=true;

allDogs.put(custName, new Dog(name, breed, age, vaccinated));

Then later on I may want to view some dog's information so I do this.

System.out.println("\nWhat is the customers name?");
System.out.println(keys);
custName = in.nextLine();

while(allDogs.get(custName) == null)
{
    System.out.println("That is not a valid name. Please try again");
    custName = in.nextLine();
}

System.out.println(allDogs.get(custName));

The problem is that when it prints out keys, all I get is an empty list.

[]

The weird part is that I was just doing this and it worked and I don't know what I changed.

I just realized what may have been different and it was that when I try to print the list that line is in an if statement. If I move the declaration of the list into the if statements then it works. So how can I make it work so that I only declare the list once and at the top of my code instead of inside the if statements?

The reason is that you are creating the list of keys as a copy of the keyset not as a reference to the keyset. So, as you update the map, the list won't update along with it.

The fix is to put the keys in printable format after filling the map.

If I'm understanding you right and you simply wanna print out the contents of a map, then just use it's toString method?

System.out.println(map.toString());

How you want it printed:

map.keySet().toString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM