wood burning stoves 2.0
The moose likes Java in General and the fly likes Dynamically create objects from a text file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Dynamically create objects from a text file" Watch "Dynamically create objects from a text file" New topic

Dynamically create objects from a text file

Mervin Chan

Joined: Dec 03, 2004
Posts: 24
How to i create objects dynamically,

Say i need to create x number of "Machine" Objects.

This is the way i create 1 machine object.

Machine a;

Machine a = new Machine (....constructor... )

Say i want to program such that i create x machine objects, the x is unknown at compile time, but is stored in a text file.

Assuming i have read the x value from the text file, how do i create x machine objects?

I want the objects to be named a1, a2, a3... ax,

for (i=0;i<x;i++)
Machine ax? //How?>???

Machine ax = new Machine(...) ///???

Any ideas? I'm stumped.


Raj Chila
Ranch Hand

Joined: Mar 18, 2004
Posts: 128

Hi you could declare an Array of Machine Type at compile time and assign the array length at run time after reading the file...so you are almost at the right path...all you need is the following...extralines of code.

Machine[] aDynArray;
// you read the x from the file...
aDynArray = new Machine[x]; //place Holder for x number of objects.
for (i=0;i<x;i++)
// you dont need this line.Machine ax? //How?>???

//Machine ax = new Machine(...) ///???

//all you need is this
aDynArray[i] = new Machine(...);
hope this helps..
I agree. Here's the link: http://aspose.com/file-tools
subject: Dynamically create objects from a text file
It's not a secret anymore!