Java – How do I add an object to a pair list in Java?

How do I add an object to a pair list in Java?… here is a solution to the problem.

How do I add an object to a pair list in Java?

List Type:

List<Pair<Integer, Pair<Integer, Integer>>> listPairOfPair = null;

I tried these but it didn’t work :

listPairOfPair.add(new Pair<Integer, Pair<Integer, Integer>>(1, (2,3));

listPairOfPair.add(new Pair<Integer, Pair<Integer, Integer>>(1, Pair.create(2,3)));

Solution

Let’s pursue “simplicity”; “Level-by-level” thing:

Pair<Integer, Integer> onePair = new Pair<>(1, 2);  assuming that you are using that android class that has this ctor

… Create a pair.

Pair<Integer, Pair<Integer, Integer>> pairOfPairs = new Pair<>(3, onePair);

… Create an integer pair and the pair you created earlier.

List<Pair<Integer, Pair<Integer, Integer>>> listOfPairedPairs = new ArrayList<>();
listOfPairedPairs.add(pairOfPairs);

… Create a list and add an element. Can be simplified a little :

listdOfPairedPairs = Arrays.asList(pairOfPairs, someOtherPair, ...);

Of course, you can write a method like this:

public Pair<Integer, Pair<Integer, Integer>> of(Integer i1, Integer i2, Integer i3) {
  ... check that uses such code and returns such a paired pair

Then use it like this:

listdOfPairedPairs = Arrays.asList(of(1,2,3) , of(4,5,6));

Of course, if you really use that android.util pair implementation; Then you’d better follow Nicolas’ advice and use Pair.create()!

Related Problems and Solutions