For some List<T> foo , for foreach loops, for example:
for(T item : foo){
is just the shorthand syntax for this idiom:
Iterator<T> iter = foo.iterator(); while(iter.hasNext()){ T item = iter.next(); // body }
To check that there are more elements in the list, you call iter.hasNext() to get the next element, you call iter.next() .
Walking through the two lists can be done by storing about 2 iterators, checking that both iterators have more elements, and then extract those elements. We can eliminate some boundary conditions in different length lists by realizing that different length lists cannot contain the same elements (since one list has more than the other).
From your description, it looks like Car contains a List<String> parts; property List<String> parts; Therefore, we can formulate a solution as:
As for your transferContents method, you have the right idea, but you cannot iterate over Car , you need to iterate over List<String> parts . To remove individual parts, you can use the remove() method, called as the add method, or remove all elements, you can call clear()
Combining this:
for (String part : c.parts) { this.parts.add(part); } c.parts.clear();
Mark elliot
source share