Jump to content
  • Advertisement
Sign in to follow this  
Hnefi

[java] Collection of references

This topic is 3030 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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.length; j++) {
map[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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!