Skip to main content
GameDev.net gamedev.net
🔒 Locked

[java] fixed 2d array, dynamic third dimension

Started by WiLD2 Jan 11, 2005 at 6:45 PM 1 replies 950+ views
Original Post
WiLD2
WiLD2
I'm working on some research for a professor and am trying to solve a problem (more a limitation) that we've come across. I've got a world that exists as a 2 dimensional array. I've populated it with 8000 moth objects that "fly" about for a fixed time. The limitation is, as would be expected, that you can only have one object per cell in an array. If a moth decided to enter a cell that was alreay occupied (unless I prevented them from doing so) the object would overwrite the other object. What I'd like to do is keep the 2 dimensional array fixed, so it is always, say, 5000 by 5000. But I want the Z-axis to be dynamic. Is it possible to occupy each cell of the 2 dimensional array with a linked list? Is that the best way to go about it? I don't think it would be very efficient to use a 3 dimensional array as that still has limitations. Thanks for the help.
---Real programmers don't comment their code. It was hard enough to write, it should be hard to understand!
tombr
tombr
You can use a 3 dimensional array. If you want to change the "Z-axis" you can replace it with a new one. Copy what references you need and throw away the old.

Or you can use a 2 dimensional array that contains a collection of your choise.
capn_midnight
capn_midnight
or you could use a 2D array of arrays

in java, there are no multi-dimensional arrays, there are arrays of arrays. This is an important distinction because it makes non-rectangular arrays possible.

this code assigns random third dimension lengths to the fixed size 4x4 grid and then prints out the size of that third dimension for each point of the grid.
public class Arrays{    public static void main (String[] args)    {        int[][][] arr = new int[4][4][];        Random r = new Random ();        for (int y = 0; y < arr.length; ++y)        {            for (int x = 0; x < arr[y].length; ++x)            {                arr[y][x] = new int[r.nextInt (10)];                for (int i = 0; i < arr[y][x].length; ++i)                {                    arr[y][x] = r.nextInt (10);                }            }        }        for (int y = 0; y < arr.length; ++y)        {            for (int x = 0; x < arr[y].length; ++x)            {                System.out.print(arr[y][x].length);            }            System.out.print('\n');        }    }}

a couple of runs of this code:
560824186054660820410227658013717258176880563752


So, no, you don't have to use a collection.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.