user2644819
user2644819

Reputation: 1827

Adding instances of class to arraylist

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.

Upvotes: 0

Views: 2748

Answers (5)

victorantunes
victorantunes

Reputation: 1169

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

Upvotes: 0

Prateek
Prateek

Reputation: 1926

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.

Upvotes: 1

Reimeus
Reimeus

Reputation: 159784

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);

Upvotes: 0

kviiri
kviiri

Reputation: 3302

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>();

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240898

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

holder.add(new Sentence(name));

Upvotes: 0

Related Questions