0

I am trying to add instanes of a class(basically a node) to my arraylist. How do i go about doing this? heres what i have:

public class Sentence {
    String word;


    public Sentence(String word){
         this.word=word;

    }

}

and then in another class:

ArrayList<Object> holder= new ArrayList<Object>();
Sentence node;
String name;
//Something to initialize/set name
holder.add(new node(name));

Bu that doesnt seem to work, i get error: cannot find symbol for node.

1
  • You don't define what a node is. You do however define what a sentence is. Commented Oct 31, 2013 at 22:59

5 Answers 5

1

Either of these should work:

holder.add(new Sentence(name)); //if name is initialized

or

holder.add(node); //if node is initialized

However, remember to actually initialize name and node before trying to use them! Also, if you intend to only store Sentence objects in the ArrayList, you could just define it as ArrayList<Sentence>:

ArrayList<Sentence> holder= new ArrayList<Sentence>();
Sign up to request clarification or add additional context in comments.

Comments

1

ArrayList<Object> holder= new ArrayList<Object>(); Here when you write this you need to specify what type of data your Arraylist can hold. In your case as you are trying to add Sentence type into your ArrayList you should change it to. ArrayList<Sentence> holder= new ArrayList<Sentence>(); specifying that ArrayList holder will be holding elements of type Sentence.

And while adding do holder.add(new Sentence(name)); because when you do holder.add(new node(name)); the compiler fails to understand what a node is. node is just a reference of type Sentence nothing else.

Comments

0

Yes what is node, constructor can be called by class name and that is Sentence

holder.add(new Sentence(name));

Comments

0

node is variable name rather than a type. Initialise name and node then the node reference can be added to the List

name = "foo";
node = new Sentence(name);
holder.add(node);

Comments

0

You can either pass an instance to an object or not. Either way works:

Sentence node = new Sentence(name);
holder.add(node);

OR

holder.add(new Sentence(name));

The decision of which to use comes up to whether you wish to use your node instance for something else other than passing it as an argument to new Node().

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.