[英]Initialize 2D Array of custom objects
我對初始化自定義對象的二維數組有疑問。
我有2個對象: CellEntity
和包含以下內容的MapEntity
:
private final ICellEntity[][] cellMap;
我初始化cellmap
在MapEntity
的構造
cellMap = new CellEntity[width][length];
但是每個CellEntity
為null
。
我想知道是否有解決方案來調用(強制) CellEntity
類中的方法以初始化CellEntity
中的每個cellMap
?
我不想修改cellMap,這是cellMap是最終版本的原因
既然你想使其最終。 您可以通過構造函數設置其值:
class MapEntity
{
private final ICellEntity[][] cellMap;
public MapEntity(ICellEntity[][] cellMap){
this.cellMap = cellMap;
}
}
您可以先創建一個初始化的cellMap數組,然后將其通過構造函數傳遞以在MapEntity中設置cellMap的值。
//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);
我想知道是否有解決方案來調用(強制)CellEntity類中的方法以初始化cellMap中的每個CellEntity?
好吧,如果您的cellMap
被聲明為final,則除了可以使用反射(我認為您不會非常喜歡 )之外,您無法通過方法(訪問器)對其進行設置。
cellMap = new CellEntity[width][length];
for(int i = 0; i < width; i++){
for(int j = 0; j < length; j++){
cellMap[i][j] = new CellEntity(); //do constructor-y stuff here
}
}
我想知道是否有解決方案來調用(強制)CellEntity類中的方法以初始化cellMap中的每個CellEntity?
實際上是可行的,但必須先創建數組。
首先在構造函數中創建數組。 創建后,我們無法更改 cellMap 的引用 ,但仍可以在其中分配值:
class TestRunner{
public static void main(String[] args){
MapEntity me = new MapEntity(5, 5);
me.initCellMap(); //init cellMap separately
}
}
class MapEntity
{
private final CellEntity[][] cellMap;
public MapEntity(int width, int length){
cellMap = new CellEntity[width][length]; //has to be done in constructor
}
public void initCellMap(){
for(int x=0; x<cellMap.length; x++)
for(int y=0; y<cellMap[0].length; y++)
cellMap[x][y] = new CellEntity();
}
}
幾乎與第一個類似,如果不想在構造函數中創建數組,則首先創建數組(個人而言,我不贊成這種方法):
class TestRunner{
public static void main(String[] args){
MapEntity me = new MapEntity();
me.initCellMap(); //init cellMap separately
}
}
class MapEntity
{
final int LENGTH = 5;
final int WIDTH = 5;
final CellEntity[][] cellMap = new CellEntity[WIDTH][LENGTH];
public MapEntity(){
}
public void initCellMap(){
for(int x=0; x<cellMap.length; x++)
for(int y=0; y<cellMap[0].length; y++)
cellMap[x][y] = new CellEntity();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.