Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize array in java when the class constructor has parameters?

I have this class constructor:

public Category(int max){
...
}

The thing is, I want to make an array of this class, how do I initialize it?

private Category categories = new Category(max)[4];

Does not work.

UPDATE

Do I need to do something like this?

private Category[] categories = new Category[4];

And then initialize each object?

like image 595
Moises Jimenez Avatar asked May 04 '12 22:05

Moises Jimenez


People also ask

How do you initialize an array of objects with parameterized constructors in Java?

One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.

Can we initialize array in constructor?

You can initialize the array variable which is declared inside the class just like any other value, either using constructor or, using the setter method.

How do you initialize a parameterized array in Java?

Array#newInstance to initialize our generic array, which requires two parameters. The first parameter specifies the type of object inside the new array. The second parameter specifies how much space to create for the array.

Can you put an array in a constructor Java?

A constructor reference is similar to method reference except that the name of a method is new. We can also create a constructor reference with an array type. For instance, if we need to create an integer array by using the constructor reference: int[]:: new, where the parameter is a length of an array.


1 Answers

When you are making an array , you are creating an array of Category. That s an instance of array.

When you are populating the array with Category objects, at that point you use the Category with Const.

Category [] categories = new Category[4];
categories[0] = new Category(10);
like image 111
DarthVader Avatar answered Oct 21 '22 12:10

DarthVader