14

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?

Akshay Pethani
  • 2,390
  • 2
  • 29
  • 42
Moises Jimenez
  • 1,962
  • 3
  • 21
  • 43

4 Answers4

19

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);
DarthVader
  • 52,984
  • 76
  • 209
  • 300
9

You can also do that in-line - make both the array and populate it with values initiated with their constructors at once. Suppose you have a class called Field that has a constructor taking two parameters and you want to construct an array of these ...

Field[] fields = new Field[]{
    new Field(1, "Record_Type"),
    new Field(3, "Record_SubType"),
    new Field(6, "Row_Number"),
    ...
};
Mr. Napik
  • 5,499
  • 3
  • 24
  • 18
7
private Category[] categories = new Category[4];

Will be instantiated with 4 null categories, you have to fill the content yourself later.
Or you can try:

private Category[] categories = {new Category(max), new Category(max), new Category(max), new Category(max)};
Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79
3

Initialize it as an array first

Category[] categories = new Categories[4];
categories[0] = new Category(max);

Then initialize each individual element.

Mike McMahon
  • 7,096
  • 3
  • 30
  • 42