Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using a Pair containing a List, but List is not acting right

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
        }
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading