我将对象存储在 HashMap 中,并且希望能够查看 HashMap 中的内容。也就是说,如果我想查看或更改我的一个对象,我想打印出键列表,以便我可以看到可用的选择。
以下是我如何将 key 转换为可打印格式的方法。
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));
问题是,当它打印出 key 时,我得到的只是一个空列表。
[]
奇怪的是,我只是这样做了,它起作用了,但我不知道我改变了什么。
我刚刚意识到可能有什么不同,那就是当我尝试打印列表时,该行位于 if 语句中。如果我将列表的声明移到 if 语句中,那么它就可以工作。那么我怎样才能让它工作,以便我只在代码顶部声明一次列表,而不是在 if 语句内?
最佳答案
原因是您将键列表创建为键集的副本,而不是作为键集的引用。因此,当您更新 map 时,列表不会随之更新。
解决方法是在填充 map 后将 key 设置为可打印格式。
关于java - 如何打印 HashMap 中的键列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24597961/