0

How should I initialize an array of classes with an empty constructor?

I can see that if I was using the constructor I would do it like so -

MyClass[] myArray = new MyClass[] {
    new MyClass(1),
    new MyClass(2),
    new MyClass(3)
};

But with an empty constructor I'm not sure what to do.

MyClass[] myArray = new MyClass[] {
    new MyClass(),
    new MyClass(),
    new MyClass()
};

This is what I have at the moment, but it seems terribly inefficient - is there a better way?

(I called it MyClass / myArray for readability in the example - don't worry, I do use sensible variable names!)

7
  • With only three members it's not really inefficient. How many do you actually expect to have? Commented Dec 22, 2011 at 21:49
  • How is it inneficient? Do you mean inneficient to program since you have to type all the new MyClass or do you think it's doing to much work at runtime? Commented Dec 22, 2011 at 21:50
  • Do you need to have three different instances of the class? Commented Dec 22, 2011 at 21:52
  • Why you consider the first as efficient and the second as inefficient? Commented Dec 22, 2011 at 21:53
  • Do you really mean "empty constructor"? Or a default (or parameter less) constructor. That's kind of confusing. Commented Dec 22, 2011 at 21:55

2 Answers 2

6

You either have to write them out one at a time, or you have to use a loop:

MyClass[] myArray = new MyClass[n];
for (int i = 0; i < myArray.length; ++i) {
    myArray[i] = new MyClass();
}
Sign up to request clarification or add additional context in comments.

Comments

0
public static <T> T[] getArray(final Class<? extends T> memberclass, final int numberOfItems) {

    final T[] array = new T[numberOfItems];
    final Constructor constr = memberclass.getConstructor(null);
    for (int index = 0; index < numberOfItems; index++) {
        array[index] = constr.newInstance(null);
    }

    return array;
}

This would a rough draft for a generic method that you can use for that purpose. Of course, I skipped all the exception handling, so this method would bloat a bit more in reality.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.