Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamically create objects from a text file

 
Mervin Chan
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
ie.

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

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

Any ideas? I'm stumped.

Thanks!

Mervin
 
Raj Chila
Ranch Hand
Posts: 128
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic