A linked list with multiple heads in Java
Posted
by
Emile
on Stack Overflow
See other posts from Stack Overflow
or by Emile
Published on 2011-01-01T12:57:56Z
Indexed on
2011/01/01
14:53 UTC
Read the original article
Hit count: 318
Hi,
I have a list in which I'd like to keep several head pointers. I've tried to create multiple ListIterators on the same list but this forbid me to add new elements in my list... (see Concurrent Modification exception).
I could create my own class but I'd rather use a built-in implementation ;)
To be more specific, here is an inefficient implementation of two basic operations and the one wich doesn't work :
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();
}
}
Emile
© Stack Overflow or respective owner