Kamrul Khan
Kamrul Khan

Reputation: 3350

How to declare array of class types in Java

I have a java code like below.

myclass a1 = new myclass(p1,p2);
myclass a2 = new myclass(p3,p4);

I want to do something like

myclass a[1] = new myclass(p1,p2);
myclass a[2] = new myclass(p3,p4);

how to do it ?

Upvotes: 0

Views: 65

Answers (3)

Salih Erikci
Salih Erikci

Reputation: 5087

myclass[] myArray = new myclass[5];

myArray[0] = new myclass(p1,p3)

This is valid in java.

Upvotes: 3

cello
cello

Reputation: 5486

it could be done in one line:

myclass[] myArray = myclass[]{ new myclass(p1, p2), new myclass(p3, p4) };

This is the same as:

myclass[] myArray = new myclass[2];
myArray[0] = new myclass(p1, p2);
myArray[1] = new myclass(p3, p4);

Upvotes: 1

Lawrence Aiello
Lawrence Aiello

Reputation: 4638

Try this:

myclass[] a = new myclass[]{
    new myclass(p1,p2),
    new myclass(p1,p2)
};

Upvotes: 1

Related Questions