有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在hashmap中打印出密钥列表?

我将对象存储在hashmap中,希望能够看到hashmap中的内容。也就是说,如果我想查看或更改我的一个对象,我想打印出一个键列表,这样我就可以看到我可用的选项

下面是我如何将密钥转换成可打印格式的

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

这是我代码的开头。然后我会以这种方式声明一些对象

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

之后我可能想查看一些狗的信息,所以我会这样做

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

问题是,当它打印出密钥时,我得到的只是一个空列表

[]

奇怪的是,我只是在做这个,它起了作用,我不知道我改变了什么

我刚刚意识到可能有什么不同,当我试图打印列表时,那一行在if语句中。如果我将列表的声明移动到If语句中,那么它就工作了。那么,我如何才能让它工作起来,使我只在代码顶部声明一次列表,而不是在if语句中声明


共 (2) 个答案

  1. # 1 楼答案

    原因是,您创建的密钥列表是密钥集的副本,而不是密钥集的引用。因此,在更新地图时,列表不会随之更新

    解决方法是在填充地图后,以可打印格式放置按键

  2. # 2 楼答案

    如果我理解的没错,你只是想打印出地图的内容,那么就用它的toString方法

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

    您希望如何打印:

    map.keySet().toString()