Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help! Array of Classes with constructors

 
Jay Beee
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic