【发布时间】:2011-01-01 12:57:56
【问题描述】:
我有一个列表,我想在其中保留几个头指针。我尝试在同一个列表上创建多个 ListIterators,但这禁止我在列表中添加新元素...(请参阅Concurrent Modification exception)。
我可以创建自己的类,但我宁愿使用内置实现;)
更具体地说,这是两个基本操作的低效实现,一个不起作用:
class MyList <E> {
private int[] _heads;
private List<E> _l;
public MyList ( int nbHeads ) {
_heads = new int[nbHeads];
_l = new LinkedList<E>();
}
public void add ( E e ) {
_l.add(e);
}
public E next ( int head ) {
return _l.get(_heads[head++]); // ugly
}
}
class MyList <E> {
private Vector<ListIterator<E>> _iters;
private List<E> _l;
public MyList ( int nbHeads ) {
_iters = new Vector<ListIterator<E>>(nbHeads);
_l = new LinkedList<E>();
for( ListIterator<E> iter : _iters ) iter = _l.listIterator();
}
public void add ( E e ) {
_l.add(e);
}
public E next ( int head ) {
// ConcurrentModificationException because of the add()
return _iters.get(head).next();
}
}
【问题讨论】:
-
您应该将您的代码放入 github 的 gist 中,或者更具体地说明您的要求。那么,您想为第二个头部“插入”元素还是更想要一个链接网络?
-
多少个“头”? 2,或任意
-
在
Collections.synchronizedList()返回的列表上做多个迭代器工作? -
同步列表不能解决我的问题。我添加了一些例子来澄清。
标签: java linked-list