-1

I want to use a List of pairs in java, each Pair containing an Integer and a List of Integers, but when I try to iterate trough each pair, the list from the pair (the second value of the pair) does not quite act as a List, meaning that I can not acces the size of this List or its elements. Any idea why? It does look like a List when printing but it surely does not have the functionality of a List. How can I access the size and elements of p.getValue1()?

import org.javatuples.Pair;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {

        List<Pair<Integer, List<Integer>>> l;
        l = new ArrayList<Pair<Integer, List<Integer>>>();
        l.add(new Pair<Integer, List<Integer>>(1, Arrays.asList(7,9,13)));

        System.out.println(l.get(0).getValue0()); //prints: 1
        System.out.println(l.get(0).getValue1()); //prints: [7,9,13], here .size() is accessible

        for(Pair p: l){
            if(p.getValue0().equals(1))
                //p.getValue1() does not act as a List here
                System.out.println(p.getValue1()); ////prints: [7,9,13], but .size() is not accessible
        }
    }
}

  • You want `if(p.getValue0() == 1)` And you're saying `System.out.println(p.getValue1().size());` won't compile or what? – g00se Nov 05 '22 at 23:40
  • Thank you for your comment. I've tried that but it's not working giving the following error: Operator '==' cannot be applied to 'java.lang.Object', 'int' – Mira Rotaru Nov 05 '22 at 23:44
  • yes, System.out.println(p.getValue1().size()) won't compile – Mira Rotaru Nov 05 '22 at 23:46
  • Something definitely wrong. `org.javatuples.Pair.getValue0()` should return type `A`which in your case is `Integer`/ Similarly, `getValue1()` should return `B`, in your case, `List` – g00se Nov 05 '22 at 23:46
  • p.getValue1() simply does not have the properties of a List in that code section and I don't know why it's acting like that – Mira Rotaru Nov 05 '22 at 23:47
  • 1
    You missed out the generics in the for loop – g00se Nov 05 '22 at 23:53

1 Answers1

1

From my comment above, you need the generics in the loop:

    // Preceding code then:    
    for (Pair<Integer, List<Integer>> p : l) {
        if (p.getValue0() == 1) {
            System.out.println(p.getValue1()); 
        }
    }

Output:

goose@t410:/tmp/tuples$ java -jar target/tuples-1.0-SNAPSHOT.jar 
1
[7, 9, 13]
[7, 9, 13]
g00se
  • 3,207
  • 2
  • 5
  • 9