I am well-aware of the costs of iterating LinkedList
with an external index (for
loop). Looking into the source code for the ListIterator
returned by LinkedList#listIterator
, I notice that it significantly speeds up the process by keeping track of the node it is currently using.
However, I recently came across this question, which was basically about iterating over two or more lists simultaneously, but needed to do so while keeping track of an index to transfer values to an array. In my mind, this made the use of iterators slightly redundant and more prone to human error, as individual declarations were necessary for each iterator, on top of looping and calling every single next
method. This is why I tried avoiding the iterator-loop combo. Here is a possible solution to the problem:
List<Integer> listOne = new ArrayList<>();
List<Integer> listTwo = new ArrayList<>();
int[] combined = new int[(listOne.size() < listTwo.size() ? listOne.size() : listTwo.size())];
for (int i = 0; i < combined.length; i++) {
combined[i] = listOne.get(i) + listTwo.get(i);
}
This is fine for ArrayList
, but it would be a rather slow operation with LinkedList
.
One possible solution would be to use the conversion constructor of ArrayList
to get all the references from a LinkedList
:
//convert linkedlists to arraylists
ArrayList<Integer> arrayListOne = new ArrayList<>(listOne);
ArrayList<Integer> arrayListTwo = new ArrayList<>(listTwo);
//iterate with an efficient get() operation
for (int i = 0; i < combined.length; i++) {
combined[i] = listOne.get(i) + listTwo.get(i);
}
Since this would only call the iterator of each LinkedList
once, and then use the more efficient ArrayList#get
method, is this a viable solution? Would the overhead from the conversion negate the efficiency gain? Are there any other downsides to this method?