I implement this interleave method in java but it doesn’t work properly. Where is my error?
I would like to mix 2 String List.
["a","b","c"]
["1","2","3","4"]
result should be = [a, 1, b, 2, c, 3, 4]
but I got only [a, 1, b, 2, c, 3].
public static List<String> interleave(List<String> list1,List<String>list2){
List<String> result= new ArrayList<String>();
for(int i=0; i<list1.size(); i++){
result.add(list1.get(i));
result.add(list2.get(i));
}
return result;
}
many thanks in advance.
regards,
koko
The error is that you’re only looking at
list1.size()whereas in your case the second list is longer than the first.You should quite possibly use the iterators instead:
You could just use the sizes, finding the minimum one and then filling in the rest afterwards, but the code’s likely to get ugly. Also, the above code is generalizable to any two
Iterable<String>values, not justList<String>.