oryan5000
oryan5000

Reputation: 91

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. Would the best method be to just create a typical 5x5 square array and place NULL values in the 6 empty cells? 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;

Array Shape

Upvotes: 2

Views: 1286

Answers (4)

Andrew
Andrew

Reputation: 49606

Would the best method be to just create a typical 5x5 square array and place NULL values in the 6 empty cells?

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. It shouldn't be a problem: a constant instance Square.EMPTY would help.

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. 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.

Upvotes: 1

johnramsden
johnramsden

Reputation: 291

By default Java arrays contain null for user-defined types if a value hasn't been set. You should just be able to set the other entries with what you want.

Upvotes: 0

ardenit
ardenit

Reputation: 3890

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];

Upvotes: 0

ddyer
ddyer

Reputation: 1788

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.

Upvotes: 1

Related Questions