dom4j-BackedList排序问题

今天在读取xml文件进行排序时,报了一个很奇怪的问题,把处理结果记录如下:

InputStream in = new FileInputStream("D:/news_02120101_0212010102.xml");
Reader reader = new InputStreamReader(in, "utf-8");
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(reader);

Element tempE = (Element) document.getRootElement().elements("channel").get(0); // item +
List<Element> list = tempE.elements("item");

Collections.sort(list, new ComparatorElement());


错误信息:
org.dom4j.IllegalAddException: The node "org.dom4j.tree.DefaultElement@da2cef [Element: <item attributes: []/>]" could not be added to the element "channel" because: The Node already has an existing parent of "channel"
at org.dom4j.tree.AbstractElement.addNode(AbstractElement.java:1533)
at org.dom4j.tree.BackedList.set(BackedList.java:92)
at java.util.AbstractList$ListItr.set(AbstractList.java:412)
at java.util.Collections.sort(Collections.java:163)
at cn.wasu.ftp.main.WinMain.main(WinMain.java:87)

原因:List<Element> list = tempE.elements("item");
这里得到的list是BackedList,这个list不允许存在重复元素,而Collections.sort方法在拷贝的时候,会使得list里面存在重复的元素,所以就报错了。

解决办法:自己new ArrayList,然后把list的节点拷贝到新的list里面。


备注1:
Collections.sort源码:
public static <T> void sort(List<T> list, Comparator<? super T> c) {
Object[] a = list.toArray();
Arrays.sort(a, (Comparator)c);
ListIterator i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set(a[j]);
}
}

参考地址:
http://sourceforge.net/p/dom4j/bugs/46/

This is not a bug: the Collections.sort() algorithm requires
the List to be fully modifiable, which is not entirely the
case with the BackedList because it does not allow duplicate
items. To sort the List, another algorithm should be used
which doesn't require that the list should allow duplicate
entries.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值