Maor Cohen
Maor Cohen

Reputation: 956

How to add an object to pair of pair list in Java?

the 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)));

Upvotes: 4

Views: 6248

Answers (2)

GhostCat
GhostCat

Reputation: 140417

Lets go for the "simply"; the "level by level" thing:

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

... creates a single Pair.

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

... creates a Pair of Integer and the previously created pair.

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

... creates the list and adds one element. That can be simplified a little bit, with:

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

And of course, you can write methods such as:

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

And use that like:

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

But of course, if you are really using that android.util Pair implementation; then you better follow the advise from Nicolas' and use Pair.create() !

Upvotes: 4

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

Assuming that you use android.util.Pair, it could simply be done as next:

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

or

listPairOfPair.add(Pair.create(1, Pair.create(2, 3)));

NB: Make sure to launch it within an Android device otherwise you will get an error of type java.lang.RuntimeException: Stub!

Upvotes: 2

Related Questions