Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing object's elements of Multiple ArrayList in java

I cannot access Multiple ArrayList element. The code is given below and it cannot access the values 5 or 6. My IDE is not accepting the last statement of my code which is System.out.println(specification.get(0).get(0).value); How can I get the elements of an Object in ArrayList which is within an array list.

class Node {

    int value;
    boolean explored;

    Node(int v) {
        value = v;
        explored = false;
    }

    int getValue() {
        return value;
    }
}

class Board {

    ArrayList<ArrayList> specification;
    ArrayList<Node> speci_node;

    Board() {
        speci_node = new ArrayList<Node>(1);
        speci_node.add(new Node(5));
        speci_node.add(new Node(6));

        specification = new ArrayList<ArrayList>(1);
        specification.add(speci_node);
        System.out.print(specification.get(0).get(0).value);  // variable 'value' is not found error....
    }
}
like image 307
Ayaz Khan Avatar asked Dec 19 '25 22:12

Ayaz Khan


2 Answers

While @YCF_L's answer is correct, you could as well specify the generic type of the inner ArrayList to avoid the cast:

specification = new ArrayList<ArrayList<Node>>(1);

Furthermore the Node and Board classes need to be in the same package, as the value member is package private and thus not accessible outside of the package of the Node class. But this already seems to be the case here...

like image 123
dpr Avatar answered Dec 22 '25 11:12

dpr


You should to cast your element like this :

System.out.print(( (Node) specification.get(0).get(0)).value);
//-----------------|-^^^-|-----------------------------------

This will return 5

like image 40
YCF_L Avatar answered Dec 22 '25 11:12

YCF_L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!