[英]How to avoid DuplicateFormatFlagsException when iterating through Map entries
Given a Map< String, Enum >, how can I Iterate through the entries, using the Map's keySet() and display the value? 给定Map <String,Enum>,如何使用Map的keySet()遍历条目并显示值? I'm only familiar with four methods of Map iteration;
我只熟悉Map迭代的四种方法。 I can get three to work and I'm uncertain why the remaining one throws an exception.
我可以让三个人工作,但我不确定为什么其余的人会抛出异常。
I've tried implementing a custom Gender.toString() method, retyping the Set<> & Map values, and inline casting of the Gender value to String. 我尝试实现自定义Gender.toString()方法,重新设置Set <>和Map值,以及将Gender值内联转换为String。
Hopefully I'm just missing something obvious but a half hour of searching yielded me no answer. 希望我只是缺少一些明显的东西,但是半小时的搜索没有给我答案。 Likely I'm wording the question wrong.
我可能在说错这个问题。 Hopefully this code can describe my question better.
希望这段代码可以更好地描述我的问题。
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() );
}
}
Any input will be greatly appreciated. 任何输入将不胜感激。 Thank you!
谢谢!
Derp's on me... After posting my question I noticed the typo. Derp在我身上...在发布我的问题后,我注意到了错字。 I forgot the converter after the %.
我忘了%之后的转换器。
System.out.printf("Key: % Value: %s\n", key, humans.get(key) ); // fault line
Should be 应该
System.out.printf("Key: %s Value: %s\n", key, humans.get(key) ); // fault line
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.