【问题标题】:How to avoid DuplicateFormatFlagsException when iterating through Map entries遍历 Map 条目时如何避免 DuplicateFormatFlagsException
【发布时间】:2014-09-15 06:29:08
【问题描述】:

给定一个 Map,我如何使用 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() );
    }
}

任何意见将不胜感激。谢谢!

【问题讨论】:

    标签: java map enums iterator set


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-19
      • 2011-05-03
      • 2022-06-28
      • 2012-04-10
      • 1970-01-01
      相关资源
      最近更新 更多