/*
* $Id: ListOfLists.java,v 1.1.1.1 2005/04/07 18:36:24 pocho Exp $
*/
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* Creates list containing other lists, access another list's elements as it would belong
* to this list.
*
* @version $Name: $ - $Revision: 1.1.1.1 $ - $Date: 2005/04/07 18:36:24 $
* TODO Test
*/
public class ListOfLists extends AbstractList {
private Collection lists = new ArrayList();
public ListOfLists(Collection c) {
Iterator it = c.iterator();
Object o;
while (it.hasNext()) {
o = it.next();
if (o instanceof List)
lists.add(o);
else if (o != null)
throw new UnsupportedOperationException(this.getClass().getName() +
" class supports only instances "+
"of java.util.List interface");
}
}
public int size() {
Iterator it = lists.iterator();
int size = 0;
Object o;
while (it.hasNext()) {
o = it.next();
if (o != null)
size += ((List) o).size();
}
return size;
}
public Object get(int index) {
int size = size();
if (index < 0)
throw new IndexOutOfBoundsException("index: " + index +"; size: " + size);
Iterator it = lists.iterator();
while (it.hasNext()) {
List list = (List) it.next();
if (index < list.size()) {
return list.get(index);
}
else
index -= list.size();
}
// if value has not been returned yet - IndexOutOfBoundsException is thrown
throw new IndexOutOfBoundsException("index: " + index +"; size: " + size);
}
/**
* Replaces the element at the specified position in underlying list with the
* specified element.
*
* @param index index of element to replace.
* @param element element to be stored at the specified position.
* @return the element previously at the specified position.
*/
public Object set(int index, Object element) {
int size = size();
if (index < 0)
throw new IndexOutOfBoundsException("index: " + index +"; size: " + size);
Iterator it = lists.iterator();
while (it.hasNext()) {
List list = (List) it.next();
if (index < list.size()) {
return list.set(index, element);
}
else
index -= list.size();
}
// if value has not been returned yet - IndexOutOfBoundsException is thrown
throw new IndexOutOfBoundsException("index: " + index +"; size: " + size);
}
public int indexOf(Object o) {
ListIterator e = listIterator();
if (o==null) {
while (e.hasNext()) {
if (e.next() == null)
return e.previousIndex();
}
}
else {
Object el;
while (e.hasNext()) {
el = e.next();
if (el.equals(o))
return e.previousIndex();
}
}
return -1;
}
public int lastIndexOf(Object o) {
ListIterator e = listIterator(size());
if (o==null) {
while (e.hasPrevious()) {
if (e.previous() == null)
return e.nextIndex();
}
} else {
Object el;
while (e.hasPrevious()) {
el = e.previous();
if (el != null && el.equals(o))
return e.nextIndex();
}
}
return -1;
}
}
|