Reputation: 309
I am creating an array of Objects, is there any way to call constructor of objects from the same line?
//Creating an array of employees
Employee[] emp=new Employee[10];
//above line creates only references pointing to null, how can i create objects
//by calling constructors in the same line?
Upvotes: 2
Views: 173
Reputation: 72284
Update: This is now possible in a one liner with Java streams:
Employee[] arr = Stream.generate(() -> new Employee())
.limit(10)
.toArray(Employee[]::new);
Original answer below, still applies to pre Java 8:
Nope, not from the same line on any sensible level - the convention is to loop through the array and fill it with objects if needed:
for(int i=0 ; i<emp.length ; i++) {
emp[i] = new Employee();
}
It's actually relatively unusual that you want to fill an array with the same objects as soon as you create it (especially in Java where List
s are more popular) thus no shorthand exists beyond the manual array initialiser approach. If you do find yourself doing this often for whatever reason, you could farm the for loop out to a separate fill()
(or similar) method, and thus at least make filling the array in this way a quick one liner.
Upvotes: 6
Reputation: 279940
You can do the completely ridiculous way
Employee[] emp = new Employee[] {new Employee(/* args */), new Employee(/* args */), new Employee(/* args */), ...} ;
But there really is no point. Use a for loop.
Java 8 introduced Arrays.setAll
which accepts a generator function that can be used to instantiate and initialize the objects to fill the array.
Arrays.setAll(emp, index -> new Employee(/* args */));
Upvotes: 3
Reputation: 938
You can either achieve this with a loop:
for(int i = 0; i < emp.length; i++) {
emp[i] = new Employee();
}
or with a direct initialization like
Employee[] emp = {new Employee(), new Employee(), ...}
I'd prefer the loop...
Upvotes: 1
Reputation: 178263
Use an array initializer:
Employee[] emp = {new Employee("Joe"), new Employee("John")};
Upvotes: 3