/** * Given a master list and the new sub list, replace the items in the master list with the * matching items from the new sub list. This process works even if the length of the new sublist * is different. * * <p>For example, givn: * * <pre> * replace A by A': * M=[A,B,C], S=[A'] => [A',B,C] * M=[A,B,A,B,C], S=[A',A'] => [A',B,A',B,C] * * when list length is different: * M=[A,A,B,C], S=[] => [B,C] * M=[A,B,C], S=[A',A'] => [A',A',B,C] * M=[B,C], S=[A',A'] => [B,C,A',A'] * </pre> */ private static List<Child> stitchList( List<Child> list, String name, List<? extends Child> newSubList) { List<Child> removed = new LinkedList<Child>(); // to preserve order, try to put new itesm where old items are found. // if the new list is longer than the current list, we put all the extra // after the last item in the sequence. That is, // given [A,A,B,C] and [A',A',A'], we'll update the list to [A',A',A',B,C] // The 'last' variable remembers the insertion position. int last = list.size(); ListIterator<Child> itr = list.listIterator(); ListIterator<? extends Child> jtr = newSubList.listIterator(); while (itr.hasNext()) { Child child = itr.next(); if (child.name.equals(name)) { if (jtr.hasNext()) { itr.set(jtr.next()); // replace last = itr.nextIndex(); removed.add(child); } else { itr.remove(); // remove removed.add(child); } } } // new list is longer than the current one if (jtr.hasNext()) list.addAll(last, newSubList.subList(jtr.nextIndex(), newSubList.size())); return removed; }