Sign in to follow this  
Hnefi

[java] Collection of references

Recommended Posts

Hnefi    386
I'm writing a game for Android, so I have to learn Java to do so. Harder than one might think when you come from a C++ background. So I'm having a problem; my game will contain a number of units, which I will want to keep in a container of some sort (probably an ArrayList or a List) so that I can quickly iterate through them and do operations on them (such as rendering them). But I also need to place the units on a map of discrete tiles. This is mostly for efficiency; if I only have a list of units, any operation that depends on finding units in a particular tile is O(n). If I can keep a pointer or reference to the units in the tilemap itself, such operations can be done in constant time. But I don't know how. In C++, this would be trivial; a barebones example of what I mean would be something like this:
struct Unit {
  int x, y;
};

struct Tile {
  Unit* unit;
};

void foo {
  list<Unit*> Units;
  Tile Map[10][10];

  Unit tank;
  unit.x = 5;
  unit.y = 8;
  Map[5][8] = &unit;
  Units.push_back(&unit);
}
Any ideas?

Share this post


Link to post
Share on other sites
Angex    884
Here is the Java syntax to your example. Hope this helps.


class Unit {
int x, y;
};

class Tile {
Unit unit;
};

public void foo {

List<Unit> units = new ArrayList<Unit>();

Tile [][] map = new Tile [10][10];

for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
map[i][j] = new Tile();
}
}

Unit tank = new Unit();

tank.x = 5;
tank.y = 8;

map[5][8].unit = tank;

units.add(tank);
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this