I have a list of lists of Integer that I'm using to build chains based on an input file. The input specifies pairs (e.g. "3, 1" indicates that 1 replaces 3 in the application), and there are overlaps in the pairs (e.g. "3, 1" and "1, 4" would mean that 1 replaces 3 and 4 replaces 1, so ultimately, 4 replaces 3).
In order to reduce all of the pairs into their final chains, I have a list containing lists of all the pairs, and then I find which entries in the list overlap and append to the chains as needed, removing the pair that has been appended to another. This is how I am attempting to do this, but I know the failure is in doubling up the iterator references:
for (ArrayList<Integer> outerChain : chains) {
for (ArrayList<Integer> innerChain : chains) {
if (outerChain.get(0).equals(innerChain.get(innerChain.size() - 1))) {
outerChain.remove(0);
innerChain.addAll(outerChain);
chains.remove(outerChain);
break;
}
}
}
As an example of the input/desired output from this operation:
{<1,3>,<2,7>,<7,9>,<8,12>,<9,1>,<6,8>}
being individual lists corresponding to input pairs, the output would be:
{<2,7,9,1,3>,<6,8,12>}
Is there a way I can nest iterators like this such that the references within each iterator are updated when removing or updating for one or the other?
Thanks in advance for the help!