pez pez - 1 year ago 75
Java Question

Create ArrayList of custom object pairs from two ArrayLists

Suppose I have two

{0, 1, 2}

I need to make a third
that contains combinations of all these. The combinations can be held in a custom object, but it should basically come out to this:
{(10, 0), (10, 1), (10, 2)}

I would need it to work similarly for two
of variable sizes.

I'm trying something like this, but it seems to have issues with out of bound exceptions for various arrays.

for (int i : array1)
for (int j : array2)
pairsArray.add(new Pair(array1.get(i), array2.get(j)));


Answer Source

Your code is correct except the line with object creation. As you're using a foreach loop you shouldn't invoke get, your i and j already contains the objects you need (in this case not actually objects but primitive ints). So your loop should look like this:

for (int i : array1) {
    for (int j : array2) {
        pairsArray.add(new Pair(i, j));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download