Java 在遍历映射项时如何避免重复FormatFlagsException
给定一个MapJava 在遍历映射项时如何避免重复FormatFlagsException,java,map,enums,iterator,set,Java,Map,Enums,Iterator,Set,给定一个Map,如何使用Map的keySet()遍历条目并显示值?我只熟悉映射迭代的四种方法;我可以让三个去工作,我不确定为什么剩下的一个会抛出异常 我尝试实现一个自定义的Gender.toString()方法,重新键入Set&Map值,并将Gender值内联转换为字符串 希望我只是错过了一些明显的东西,但半小时的搜索没有给我答案。很可能我把问题的措辞弄错了。希望这段代码能更好地描述我的问题 public enum Gender { MALE, FEMALE; } public static
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() );
}
}
公共枚举性别{男性,女性;}
公共静态void main(字符串[]args)
{
Map humans=新HashMap();
人类。put(“塞缪尔”,性别。男性);
人类。put(“布莱斯”,性别。男性);
人类。put(“康拉德”,性别。男性);
人类。put(“安吉”,性别。女性);
System.out.println(“for.keyset()”);
Set ks=humans.keySet();
for(字符串键:ks)
{
System.out.printf(“键:%s值:%s\n”,键,humans.get(键));
}
System.out.println(“\n.entrySet()”);
Set entrySet=humans.entrySet();
for(Map.Entry:entrySet)
{
System.out.printf(“键:%s值:%s\n”,entry.getKey(),entry.getValue());
}
//***--->因DuplicateFormatFlagsException而失败
System.out.println(“\n while.keyset().iterator()”;
Set ks2=humans.keySet();
迭代器keystiterator=ks2.Iterator();
while(keySetIterator.hasNext())
{
String key=keysiterator.next();
System.out.printf(“Key:%Value:%s\n”,Key,humans.get(Key));//错误行
}
System.out.println(“\n while.entrySet().iterator()”;
Set entrySet2=humans.entrySet();
迭代器entrySetIterator=entrySet2.Iterator();
while(entrySetIterator.hasNext())
{
Map.Entry=entrySetIterator.next();
System.out.printf(“键:%s值:%s\n”,entry.getKey(),entry.getValue());
}
}
任何意见都将不胜感激。谢谢大家! 德普在我身上。。。在发布我的问题后,我注意到了拼写错误。我忘记了在%之后的转换器
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