Fix potential NullPointerExceptions when retrieving entities from a sector.

This commit is contained in:
Major-
2014-07-10 18:21:30 +01:00
parent 3654d28b18
commit 337322f491
2 changed files with 24 additions and 5 deletions
+1 -1
View File
@@ -289,7 +289,7 @@ public final class World {
boolean success = true; boolean success = true;
for (Entity entity : entities) { for (Entity entity : entities) {
Sector sector = sectorRepository.get(SectorCoordinates.fromPosition(entity.getPosition())); Sector sector = sectorRepository.fromPosition(entity.getPosition());
success &= sector.addEntity(entity); success &= sector.addEntity(entity);
} }
return success; return success;
+23 -4
View File
@@ -86,7 +86,15 @@ public final class Sector {
* @return {@code true} if this sector contains the entity, otherwise {@code false}. * @return {@code true} if this sector contains the entity, otherwise {@code false}.
*/ */
public boolean contains(Entity entity) { public boolean contains(Entity entity) {
return entities.get(entity.getPosition()).contains(entity); Position position = entity.getPosition();
List<Entity> entities = this.entities.get(position);
if (entities == null) {
this.entities.put(position, new ArrayList<>());
return false;
}
return this.entities.get(position).contains(entity);
} }
/** /**
@@ -105,7 +113,13 @@ public final class Sector {
* @return The list. * @return The list.
*/ */
public List<Entity> getEntities(Position position) { public List<Entity> getEntities(Position position) {
return new ArrayList<>(entities.get(position)); List<Entity> entities = this.entities.get(position);
if (entities == null) {
entities = new ArrayList<>();
this.entities.put(position, entities);
}
return new ArrayList<>(entities);
} }
/** /**
@@ -117,8 +131,13 @@ public final class Sector {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T extends Entity> List<T> getEntities(Position position, EntityType type) { public <T extends Entity> List<T> getEntities(Position position, EntityType type) {
return (List<T>) entities.get(position).stream().filter((e) -> e.getEntityType() == type) List<Entity> entities = this.entities.get(position);
.collect(Collectors.toList()); if (entities == null) {
entities = new ArrayList<>();
this.entities.put(position, entities);
}
return (List<T>) entities.stream().filter((e) -> e.getEntityType() == type).collect(Collectors.toList());
} }
/** /**