6

Initialize 2D Array of Custom Objects

 3 years ago
source link: https://www.codesd.com/item/initialize-2d-array-of-custom-objects.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Initialize 2D Array of Custom Objects

advertisements

I've a question about initializing a 2D Array of custom objects.

I have 2 Objects : a CellEntity, and a MapEntity who contains:

private final ICellEntity[][] cellMap;

I've initialized cellmap in the MapEntity's constructor

cellMap = new CellEntity[width][length];

but every CellEntity is null.

I want to know if there's a solution to invoke (to force) a method in CellEntity class in order to init each CellEntity in the cellMap?


I dont want to modify the cellMap it's the reason why cellMap is final

Since you want to make it final. You can set it's value via the constructor:

class MapEntity
{
    private final ICellEntity[][] cellMap;

    public MapEntity(ICellEntity[][] cellMap){
        this.cellMap = cellMap;
    }
}

You can create an initialized cellMap array first, then pass it via the constructor to set the cellMap's value within MapEntity.

//Initialize your cellMap else where first
ICellEntity[][] cellMap = new CellEntity[width][length];
for(int x=0; x<width; x++)
    for(int y=0; y<length; y++)
        cellMap[x][y] = new CellEntity();

//Pass in the initialized cellMap via the constructor
MapEntity mapEntity = new MapEntity(cellMap);

I want to know if there's a solution to invoke (to force) a method in CellEntity class in order to init each CellEntity in the cellMap?

Well, if your cellMap was declared as final, there is no way you can set it via a method (accessor), other than probably using reflection (which I don't think you will like it very much).


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK