URL87
URL87

Reputation: 11012

Array of classes which create instances

having Obj class which in his constructor has System.out.println("Hello world!") ;

I create an array of this class using - Obj[] objArray = new Obj[10] ; and nothing printed , means - no instance of Obj has been called . Is there any way to create such array ,but with instances , beyond create them in for loop ?

Upvotes: 0

Views: 638

Answers (4)

Hot Licks
Hot Licks

Reputation: 47729

Obj[] objArray = new Obj[10] ; just creates an array capable of holding 10 Objs. To place Objs into the array you need to either use Rohit's approach or write a simple for loop to initialize the array entries one at a time:

for (int i = 0; i < 10; i++) {
    objArray[i] = new Obj();
}

Or, without a for loop:

int i = 0;
while (i < 10) {
    objArray[i] = new Obj();
    i++;
}

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213243

Well, since you want to know a way apart from using a for loop, you can do this: -

Obj[] objArray = {new Obj(), new Obj(), new Obj()};

What happens here is, you are initializing your array reference directly with array elements. Now the type of actual array object is inferred from type of array reference on the LHS.

So, with that declaration, an array of size 3 (in the above case) is created, with each index in the array initialized with the instance of Obj class in the given order.


A better way that I would suggest is to use an ArrayList, in which case, you have double-braces initialization to initialize your List without for loop. And plus with an added advantage that you can anytime add new elements to it. As it dynamically increasing array.

List<Object> list = new ArrayList<Object>() {
    {
        add(new Obj());
        add(new Obj());
        add(new Obj());
    }
};  // Note the semi-colon here.

list.add(new Obj());  // Add another element here.

Upvotes: 3

nullpotent
nullpotent

Reputation: 9260

Answers so far are good and helpful. I'm here just to remind you about

Obj[] objArray = new Obj[10];
Arrays.fill(objArray, new Obj());

Though, this will only assign one reference (to a new Obj()) to all of the elements of array.

Upvotes: 3

Jatin
Jatin

Reputation: 31724

When you do Obj[] objArray = new Obj[10] ; You only create an array of references to point to the actual 'Obj` object.

But in your case the actual Obj object is never created.

for (int i = 0; i < objArray.length; i++) {
objArray[i] = new Obj();
}

Doing above will print the desired.

Finally do System.out.println(Arrays.deepToString(objArray)) to print toString() of all the Obj

Upvotes: 1

Related Questions