pez pez - 2 months ago 5
Java Question

Create ArrayList of custom object pairs from two ArrayLists

Suppose I have two

ArrayList
:
{10}
and
{0, 1, 2}


I need to make a third
ArrayList
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
ArrayList
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)));
}
}


Thanks!

Answer

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));
    }
}
Comments