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....
}
}
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...
You should to cast your element like this :
System.out.print(( (Node) specification.get(0).get(0)).value);
//-----------------|-^^^-|-----------------------------------
This will return 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With