3

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....
    }
}
4
  • 1
    What is the error you are getting? Commented Mar 4, 2017 at 19:59
  • the IDE is not accepting the last statement. It is say variable 'value' is not found Commented Mar 4, 2017 at 20:01
  • Are both classes are in the same file? Or are they in different files and maybe different packages as well? Commented Mar 4, 2017 at 20:06
  • no, for understanding i have merge them here Commented Mar 4, 2017 at 20:08

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

You should to cast your element like this :

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

This will return 5

6 Comments

There's no need to cast if you declare the generic type correctly
it still a solution @FedericoPeraltaSchaffner my answer help the OP so why this down-vote?
mmmm @FedericoPeraltaSchaffner ok :)
Because of what I stated in my previous comment: there's no need to cast if the outer ArrayList is correctly declared. If you edit your question and clarify this point, I will gladly undo my downvote
My answer help the OP and it still a way to solve this problem, maybe the OP need it like this there are many solutions @FedericoPeraltaSchaffner ok you are free to make down-votes, i don't mind
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.