简体   繁体   English

如何在Java中创建一个不规则形状的二维数组

[英]How to create an irregular shaped two dimensional array in Java

I need to create a two dimensional array for a card game as seen in the image below.我需要为纸牌游戏创建一个二维数组,如下图所示。 The array has 5 total rows, the top two containing 5 columns each and the bottom three rows containing three columns each.该数组共有 5 行,前两行每行包含 5 列,底部三行每行包含三列。 Would the best method be to just create a typical 5x5 square array and place NULL values in the 6 empty cells?最好的方法是创建一个典型的 5x5 方形数组并将 NULL 值放在 6 个空单元格中吗? Or is there a more sophisticated way to do this for oddly shaped 2D arrays?或者是否有更复杂的方法来处理形状奇特的二维数组?

Square[][] Board = new Square[5][5];
board[5][5] = NULL;

阵列形状

There's no better way except not to use an array at all.除了根本不使用数组之外,没有更好的方法。 In any case, you'll want to use an accessor function that deals with array bounds and empty slots in some uniform way, rather than depend on every user of the data structure to know about the bounds and the possibility of NULL entries.在任何情况下,您都希望使用访问器函数以某种统一的方式处理数组边界和空槽,而不是依赖于数据结构的每个用户来了解边界和 NULL 条目的可能性。

Would the best method be to just create a typical 5x5 square array and place NULL values in the 6 empty cells?最好的方法是创建一个典型的 5x5 方形数组并将 NULL 值放在 6 个空单元格中吗?

Yes, I think it would be the most intuitive solution.是的,我认为这将是最直观的解决方案。 Keep in mind you need to distinguish an empty call and empty card cell, so you can't use null for both.请记住,您需要区分空呼叫和空卡单元格,因此不能对两者都使用 null。 It shouldn't be a problem: a constant instance Square.EMPTY would help.这应该不是问题:常量实例Square.EMPTY会有所帮助。

A two-dimensional array is the best data structure for this kind of games.二维数组是这类游戏最好的数据结构。 If you can come up with a method that tells what the boundaries are and how to iterate over the board nicely, you will be fine.如果你能想出一种方法来说明边界是什么以及如何很好地迭代板,你会没事的。

Or is there a more sophisticated way to do this for oddly shaped 2D arrays?或者是否有更复杂的方法来处理形状奇特的二维数组?

I can't think of any.我想不出任何。 You could have你可以有

Square[][] board = new Square[MAX][];

board[2] = new Square[MAX];
board[3] = new Square[NOT_MAX];

but for arrays of length NOT_MAX , you additionally need to store an offset.但是对于长度为NOT_MAX数组,您还需要存储一个偏移量。 It complicates things and assumes the pattern stays always as simple as you've shown.它使事情复杂化,并假设模式始终如您所展示的那样简单。 For a pattern with gaps in between, it won't work.对于中间有间隙的模式,它不起作用。

You can create your array like this:您可以像这样创建数组:

Square[][] board = new Square[5][];
board[0] = new Square[5];
board[1] = new Square[5];
board[2] = new Square[3];
board[3] = new Square[3];
board[4] = new Square[3];

By default Java arrays contain null for user-defined types if a value hasn't been set.默认情况下,如果尚未设置值,则 Java 数组包含用户定义类型的null You should just be able to set the other entries with what you want.您应该能够根据需要设置其他条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM