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

I have this class constructor:

public category (int max) {,,,}

The fact is that I want to create an array of this class, how to initialize it?

private Categories of categories = new category (max.) [4];

Does not work.

UPDATE

Do I need to do something?

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

And then initialize each object?

+6
source share
4 answers

When you create an array, you create an array of the category. This is an example of an array.

When you populate an array with Category objects, at this point you are using a category with Const.

Category [] categories = new Category[4]; categories[0] = new Category(10); 
+12
source
 private Category[] categories = new Category[4]; 

An instance with 4 null categories will be created, you must fill in the content yourself later. Or you can try:

 private Category[] categories = {new Category(max), new Category(max), new Category(max), new Category(max)}; 
+5
source

Initialize it as an array first

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

Then initialize each individual element.

+3
source

You can also do this in a line - make an array and fill it with the values ​​started with their constructors right away. Suppose you have a class called "Field" that has a constructor with two parameters, and you want to build an array of these ...

 Field[] fields = new Field[]{ new Field(1, "Record_Type"), new Field(3, "Record_SubType"), new Field(6, "Row_Number"), ... }; 
+2
source

Source: https://habr.com/ru/post/914935/


All Articles