Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Java in General and the fly likes Help! Array of Classes with constructors Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Help! Array of Classes with constructors" Watch "Help! Array of Classes with constructors" New topic
Author

Help! Array of Classes with constructors

Jay Beee
Greenhorn

Joined: Oct 11, 2003
Posts: 2
Hey, quick question. How do I create an array of Classes and pass an argument to the constuctor?
public ClassData(int stuff) {
}
//////
class_array = new ClassData[10];
how do I pass a value for stuff in the ClassData constructor?
??? class_array = new ClassData(stuff)[10]; ??? doest compile

thanx
p.s. i a c++ programmer trying to learn java.
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1871
Hi Jay
Well, you seem to want pass same initial value to all the 10 objects of ClassData right?
When we write, class_array = new ClassData[10]; it just allocates 10 element array that can contain objects of type ClassData. It doesn't create any object of ClassData. We have to run for loop from i =1 to 10 where we write,
class_array[i] = new ClassData(myStuffValue);
OR we can write,
class_array = new ClassData[]{ new ClassData(myStuffValue), new ClassData(myStuffValue), new ClassData(myStuffValue), new ClassData(myStuffValue)};
if we want to have 4 element array but its easier to follow for loop instead...
Regards
Maulin
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help! Array of Classes with constructors