0

Question2:

I'm confused on ArrayList<Object>, please explain to me the following:

I have a class Node which has two fields: data1 and data2

public class Node {
    private static int data1;
    private static int data2;
 
    public Node(){...}
    public static void setData1(int data);
    public static void getData1();
    public static void setData2(int data);
    public static void getData2();
} // end of class Node

And then I have another class called Link.

public class Link {
    private ArrayList<Node> linkList = new ArrayList<Node>();
    private Node node = new Node();
    ...
    linkList.add(node)
    linkList.get(how to do it here)
} // end of class Link

I want to output the Node data inside linkList.

linkList.get(how to do it here)

How would I do that?

4
  • 1
    Are you getting an error? Or have you tested it, and it doesn't work correctly? Commented Nov 13, 2012 at 6:11
  • maybe you need to create an instance of your ArrayList<node>. Commented Nov 13, 2012 at 6:11
  • 1
    how is it not working, are you getting an exception, or is it silently failing? Have you tried debugging to see that linkList.add(nodelist) is actually being called? Btw, normal convention for Java is for classnames to start with an uppercase letter. Commented Nov 13, 2012 at 6:12
  • it give me exception "Exception in thread "main" java.lang.NullPointerException" Commented Nov 13, 2012 at 6:15

2 Answers 2

1

I think you simply forgot to do something like

private ArrayList<node> linkList = new ArrayList<node>();

Try:

public class Link {
    private ArrayList<node> linkList = new ArrayList<node>();
    private node nodelist = new node();
    ...
    linkList.add(nodelist)
} // end of class link

EDIT

Take a look to the following sample code taken from here to understand how to work with ArrayList<...>

java.util.ArrayList<String>  v = new java.util.ArrayList<String>();
    v.add( "able" );
    v.add( "baker" );
    v.add( "charlie" );
    v.add( "delta" );

int n = v.size();
for(int i = 0; i < n ; i++)
    System.out.println( v.get( i ) );
Sign up to request clarification or add additional context in comments.

2 Comments

furthermore, if i want to output the linklist, i try linkList.get(0) linkList.get(node.getData()) wrong again !!
i edited the answer. You should accept it if it solves your problem and better open a new one if you have a new question. otherwise it is hard to follow and help for other people if you change your original question to ask something new.
1

OP solved it by using:

linkList.get(0).getData();

Comments

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.