将HashMap添加到TreeSet的奇怪行为

时间:2013-08-21 18:40:55

标签: java map set

HashMap<String,String>添加到TreeSet<HashMap<String,String>>时出现以下问题。代码如下:

... Do something
XMLRoot root = XMLRoot
.newBuild()
.setTrx(
    Tag
    .newBuild()
    .setName("trx")
    .addAttribute("type", "04/01")
    .addAttribute("id", id));
... => BreakPoint here!

现在addAttribute()方法的作用是:

public Tag addAttribute(String name, String value) {
    // Create the attribute.
    HashMap<String, String> att = new HashMap<String, String>();
    att.put(name, value);

    attributes.add(att);
    return this;
}

attributes变量是TreeSet<HashMap<String,String>>类型的集合。现在使用Netbeans调试器我在创建XMLRoot对象后立即添加了一个BreakPoint,我发现它永远不会到达断点。问题是没有抛出异常,没有错误,没有。另一个奇怪的事情是,如果我使用addAttribute()方法只添加一个元素,那么一切正常。

问题:可能导致执行在第二个元素的TreeSet类的add()方法内终止的原因......?

注意:使用调试器我设法看到第一个属性被设置,但我从未到达第二个属性,这意味着执行在添加第二个元素时突然结束。

详细信息:Apple JDK 1.6.0_51 64位OSX 10.8.4(Mountain Lion)

1 个答案:

答案 0 :(得分:1)

您几乎肯定会收到ClassCastException,因为TreeSet的元素必须实现Comparable,而HashMap则不能。说实话,我很惊讶编译器允许这样做;我认为TreeSet在参数化方面会更明确。

你说你在事件发送线程上运行它。 EDT有一个未捕获的异常处理程序,通常在StdErr上打印异常,但忽略它们。如果您没有看到消息,则可以使用您的应用程序替换此处理程序。