Re: Possible to create an array and call object constructors at the
same time?
laredotornado wrote:
On Dec 4, 2:31 pm, Eric Sosman <esos...@ieee-dot-org.invalid> wrote:
laredotornado wrote:
Hi,
I'm using Java 1.6. I was wondering if there is a shorter way to do
this. I initialize my array and then loop through the array,
assigning a newly created element at each step ...
DatePref[] prefs = new DatePref[arraySize];
for (int i=0; i<prefs.length; i++) {
prefs[i] = new DatePref();
...
}
I was wondering if there was a more all-in-one solution for
initializing the array and automatically calling the constructor for
each object in the array.
DatePref[] prefs = {
new DatePref(),
new SubclassOfDatePref(),
new AnotherSubclassOfDatePref(),
new StillAnotherSubclassOfDatePref(),
};
Not an enormously practical construct, and no use at all
if arraySize isn't known at code-writing time. The choice of
initializers is meant to illustrate one problem with the idea;
"Others will occur to your thought."
It is fine if we change the rules to use
some type of Collection as opposed to an Object[] .
I'm not sure what you mean by this.
--
Eric Sosman
esos...@ieee-dot-org.invalid
Please don't quote signatures.
In other words, I use
DatePref[] prefs = new DatePref[arraySize];
in my example, but I could have used
ArrayList arrayList = new ArrayList();
so long as I can populate ArrayList with an "arraySize" (value not
known at compile time) number of objects, each with a different
reference without having to use a loop. Hope that makes more sense,
although I'm sensing it is not possible to do what I was asking.
If you could solve the first problem, you could then do
ArrayList<DatePref> = new ArrayList<DatePref>(
Arrays.asList(prefs));
However, I'm doubtful about the usefulness of the shortcut
in the first place. The magically populated array would be
useful if you needed N instances, all created by the no-arguments
constructor and hence all "identical" (unless the constructor is
supplying a serial number or a high-precision time stamp or a
random initial value or some such). Having N "identical" objects
floating around may sometimes be useful, but not often: What good
are N immutable zero-valued Integers, for example? Perhaps you
will go on to "customize" the (mutable) new objects -- but if
you're writing a customization loop, you might as well construct
them at the same time. Usually, anyhow.
Do you have a concrete example of a situation you've actually
encountered where the ability to create an array and populate it
with N identical objects would have come in handy? Last time this
topic came around (six-ish months ago, I think, but I wouldn't
swear to it), lots of contrived "if you ever wanted to X" examples
were offered, but I don't recall seeing any "this actually happened
to me" accounts.
--
Eric Sosman
esosman@ieee-dot-org.invalid