给定一个 Map< String, Enum >,如何使用 Map 的 keySet() 迭代条目并显示值?我只熟悉Map迭代的四种方法;我可以让三个工作,但我不确定为什么剩下的一个会抛出异常。
我尝试实现自定义 Gender.toString() 方法,重新输入 Set<> 和 Map 值,并将 Gender 值内联转换为 String。
希望我只是错过了一些明显的东西,但半小时的搜索没有给我带来答案。可能我的问题措辞错误。希望这段代码可以更好地描述我的问题。
public enum Gender { MALE, FEMALE; }
public static void main (String[] args)
{
Map<String,Gender> humans = new HashMap<String,Gender>();
humans.put("Samuel", Gender.MALE);
humans.put("Bryce", Gender.MALE);
humans.put("Conrad", Gender.MALE);
humans.put("Angie", Gender.FEMALE);
System.out.println("for .keyset()");
Set<String> ks = humans.keySet();
for (String key : ks)
{
System.out.printf("Key: %s Value: %s\n", key, humans.get(key));
}
System.out.println("\nfor .entrySet() ");
Set<Map.Entry<String,Gender>> entrySet = humans.entrySet();
for (Map.Entry entry : entrySet)
{
System.out.printf("Key: %s Value: %s\n", entry.getKey(), entry.getValue());
}
// ***---> FAILS with DuplicateFormatFlagsException
System.out.println("\nwhile .keyset().iterator()");
Set<String> ks2 = humans.keySet();
Iterator<String> keySetIterator = ks2.iterator();
while (keySetIterator.hasNext())
{
String key= keySetIterator.next();
System.out.printf("Key: % Value: %s\n", key, humans.get(key) ); // fault line
}
System.out.println("\nwhile .entrySet().iterator()");
Set<Map.Entry<String,Gender>> entrySet2 = humans.entrySet();
Iterator<Map.Entry<String,Gender>> entrySetIterator = entrySet2.iterator();
while (entrySetIterator.hasNext())
{
Map.Entry<String,Gender> entry = entrySetIterator.next();
System.out.printf("Key: %s Value: %s\n", entry.getKey(), entry.getValue() );
}
}
任何意见都将不胜感激。谢谢!
最佳答案
Derp 对我有兴趣...在发布我的问题后,我注意到了拼写错误。我忘记了 % 之后的转换器。
System.out.printf("Key: % Value: %s\n", key, humans.get(key) ); // fault line
应该是
System.out.printf("Key: %s Value: %s\n", key, humans.get(key) ); // fault line
关于java - 迭代 Map 条目时如何避免 DuplicateFormatFlagsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24921204/