1

I have two arrays with different Objects.

ArrayList<Array1> array1 = new ArrayList<>();
ArrayList<Array2> array2 = new ArrayList<>();

I want to merge these arrays to

ArrayList<Object> array = new ArrayList<>();

with pattern, for every 3-4 item in array1, add item in array2.

How can I do this?

3
  • Not enough information: what is you assumption about the list sizes ? What do you want to do with elements that were not added ? ignore them ? Commented Feb 9, 2018 at 4:43
  • "How can I do this?" You write some code. Well, first you decide whether it's 3 or 4, i.e. complete the specification of what you intend to do. --- idownvotedbecau.se/noattempt Commented Feb 9, 2018 at 4:54
  • Just a side note, it's quite a bad idea to name an arraylist as array. Commented Feb 9, 2018 at 4:58

1 Answer 1

3

You could keep things simple and just use a loop:

for (int i=0; i < array1.size(); ++i) {
    array.add(array1.get(i));
    if ((i+1) % 4 == 0) {
        array.add(array2.get(i/4));
    }
}

The logic of the above loop is that each iteration always adds an item from array1 to the final list. In addition, after adding 4 items from array1 it adds an item from array2.

I have assumed here that array2 has enough elements to support covering the enitre array1 list. Should you plan on doing this in production, you might want to check for this edge case.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.