dreamer - 9 months ago 230

Java Question

Write a method

public static ArrayList merge(ArrayList a, ArrayList b)

that merges two array lists, alternating elements from both array lists. If one array list is shorter than the other, then alternate as long as you can and then append the remaining elemts from the longer array list. For example, if a is

1 4 9 16

and b is

9 7 4 9 11

then merge returns the array list

1 9 4 7 9 4 16 9 11

What I tried doing was writing a for loop with if statements such that a number is added to the merge array list from array list a when i is an even number (i%2==0) and from array list b when i is an odd number. I am however not sure how to deal with the fact that one array list can be longer than the other. Could anyone please help me out?

`public static ArrayList<Integer> merge(ArrayList<Integer> een, ArrayList<Integer> twee)`

{

ArrayList<Integer> merged = new ArrayList<Integer>();

for(int i = 0; i<100; i++)

{

if(i%2!=0)

{

merged.add(a.get(i));

}

if(i%2 == 0)

{

merged.add(b.get(i));

}

}

System.out.println(merged);

return merged;

}

Answer

Without Iterator:

```
public static ArrayList merge(ArrayList a, ArrayList b) {
int c1 = 0, c2 = 0;
ArrayList<Integer> res = new ArrayList<Integer>();
while(c1 < a.size() || c2 < b.size()) {
if(c1 < a.size())
res.add((Integer) a.get(c1++));
if(c2 < b.size())
res.add((Integer) b.get(c2++));
}
return res;
}
```