The problem with your previous implementation was that the invocation of next() was inside a condition which shouldn't have been the case. Also, you can again avoid casts by declaring next as E next = null;
.
Again, like I said, making the method accept a Collection is plain wrong since a Collection doesn't support the notion or is not aware of indexed/ordered access. Your custom list implementation should accept only a List which would make your class semantically correct.
Anyways, here is my stab at it:
public class LinkedListTest {
public static void main(final String[] args) {
testNormal();
testEmpty();
testNull();
}
private static void testNormal() {
List<Integer> list = new ArrayList<Integer>();
list.add(10); list.add(20); list.add(30); list.add(40);
NodeList<Integer> nodeList = new NodeList<Integer>();
nodeList.add(1);
nodeList.addAll(2, list);
System.out.println(nodeList);
}
private static void testNull() {
NodeList<Integer> nodeList = new NodeList<Integer>();
nodeList.add(1);
nodeList.addAll(2, null);
System.out.println(nodeList);
}
private static void testEmpty() {
List<Integer> list = new ArrayList<Integer>();
NodeList<Integer> nodeList = new NodeList<Integer>();
nodeList.add(1);
nodeList.addAll(2, list);
System.out.println(nodeList);
}
}
class NodeList<E> extends LinkedList<E> {
private static final long serialVersionUID = 1L;
public boolean addAll(final int startIdx, final Collection<? extends E> collection) {
if (collection == null || collection.isEmpty()) {
return false;
}
final int size = collection.size();
if (startIdx < 0 || startIdx > size - 1) {
throw new IndexOutOfBoundsException(
"An out of bounds index specified: " + startIdx);
}
int i = 0;
boolean collectionChanged = false;
for (Iterator<? extends E> iter = collection.iterator(); iter.hasNext(); ++i) {
E elem = iter.next();
if …