Hey, so I've just written this piece of code for my server, what it does is search for all of the CacheObject's within your region based on the name in the parameter, and finds the closest one to you.
It works, but I was wondering if I could get some feedback and advice on how I can improve my code.
Code:
/**
* Finds the closest cache object in the bot's region, based on its name.
*
* @param name the name.
* @return the cache object.
*/
public CacheObject searchForClosestCacheObject(String name) {
Regions r = World.getWorld().getRegionManager().getRegionByLocation(getPosition());
int[][] objData = new int[0][3];
int count = 0;
for (CacheObject object : r.getGameObjects()) {
if (object == null) {
continue;
}
GameObjectData data = GameObjectData.forId(object.getDef().getId());
if (data == null) {
continue;
}
if (data.getName().equalsIgnoreCase(name)) {
count++;
objData = new int[count + 1][3];
objData[count][0] = Misc.getDistance(object.getLocation(), getPosition());
objData[count][1] = object.getLocation().getX();
objData[count][2] = object.getLocation().getY();
}
}
int lowestDistance = objData[0][0];
Position objectPosition;
CacheObject object = null;
for (int i = 0; i < objData.length; i++) {
if (objData[i][0] == -1) {
continue;
}
if (objData[i][0] < lowestDistance) {
lowestDistance = objData[i][0];
objectPosition = new Position(objData[i][1], objData[i][2], getPosition().getZ());
object = ObjectLoader.object(objectPosition.getX(), objectPosition.getY(), getPosition().getZ());
}
}
return object;
}
I know that there must be a better way of doing this, possible a Map<Integer, Position>? I never have really worked with Maps/Hashmaps, so, I just used a 2D array. Thanks.