我在添加 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 对象后立即添加了一个断点,但我发现它永远不会到达断点。问题是没有抛出异常,没有错误,什么也没有。另一件奇怪的事情是,如果我使用 addAttribute()
仅添加一个元素方法然后一切正常。
问题:什么可能导致第二个元素的 TreeSet 类的 add() 方法内的执行终止...?
注意:使用调试器,我设法看到第一个属性被设置,但我从未到达第二个属性,这意味着在添加第二个元素时执行突然结束。
详细信息: Apple JDK 1.6.0_51 64 位 OSX 10.8.4 (Mountain Lion)
最佳答案
您几乎肯定会遇到 ClassCastException
,因为 TreeSet
的元素必须实现 Comparable
而 HashMap
则不然。老实说,我很惊讶编译器允许这样做;我认为 TreeSet
的参数化会更加明确。
您说您正在事件调度线程上运行它。 EDT 有一个未捕获的异常处理程序,通常在 StdErr 上打印异常,但在其他情况下会忽略它们。如果您没有看到消息,则该处理程序可能已被您的应用程序替换。
关于java - 将 HashMap 添加到 TreeSet 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18365220/