More Efficient Way of making multiple objects

夙愿已清 提交于 2019-12-21 23:24:41

问题


I am trying to make a memory game with Java. The game is basically going to be some squares in a grid that is 4x4 at the moment just for testing purposes. I have created my Square class, and programmed what i want them to do in that class, and then created a square object in another Class that handles the "Normal Mode" of the game. Now since i have a 4x4 grid of squares I need to make 16 different Squares (Or at least that's what i'm thinking at the moment). I also need to draw the Squares in their corresponding place.

My Question: What is the most efficient way of creating 16 of these Square objects while still being able to manipulate them individually? (Sort of like each having their own name; Square, Square1, Square2, etc).

I am also using the Slick2D library.


回答1:


As mentioned above, Square[][] squareGrid = new Square[4][4] is a good way to go about this; then you can initialize all 16 of them using:

 for (int i = 0; i < squareGrid.length; i++)
        for(int j = 0; j < squareGrid[i].length; j++)
            squareGrid[i][j] = new Square();

now each square automatically has its own unique (row, col) id. for example,

squareGrid[1][2].callSomeFunctionInSquareClass();

can be used to manipulate the square at 2nd row, 3rd column. This way you will avoid scanning through all the squares to get the one at a particular cell on the grid, thus making it much more efficient.

happy coding :)




回答2:


You can try Square[][] grid = new Square[4][4]




回答3:


I would use a Square[][] array, e.g. Square[][] squares = new Square[4][4], and then initialise it with all 16 Squares in two nested loops:

for (int x = 0; x < squares.length) x++)
    for (int y = 0; y < squares[x].length; y++)
        squares[x][y] = new Square(x, y);


来源:https://stackoverflow.com/questions/20896694/more-efficient-way-of-making-multiple-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!