What is the simplest way in Java to create an array/list/vector of specified size filled with instances of classes created with the default constructor (I hope this term is used outside C++ also?). I want to make the code more readable and reduce the risk of NullPointerException.
(For example, the ArrayList constructor has a constructor with argument for capacity, not size..)
Below is what is try to achieve in code. This is your typical approach. (It could be done with Vector or ArrayList also)
// Typical, I don't want this
class SomeSimpleClass {
DataClass[] data = new DataClass[10];
SomeSimpleClass() {
// I don't want this..
for(int i = 0; i < 10; i++) data[i] = new DataClass();
}
void doSomething() {
data[5].doSomething();
}
}
// What I want
class SomeSimpleClass
// now I have ten data objects, ready to be used...
Holder<DataClass> data = new Holder<DataClass>(10);
void doSomething() {
data.get(5).doSomething();
}
}
I find that quite many of my classes require a few instances of smaller, data-holding classes. The above example is simple but it can be a real nuisance when the class becomes more complicated.
What is the best approach here? Are there some holder classes that work like above? Are there functions for ArrayList (or similar class) such as below?
ArrayList<DataClass> data = new ArrayList<DataClass>().addNewObjects(10);