I have the following class:
public abstract class MapObjects<MapleMapObject> {
private Map map;
private HashMap<Integer, MapleMapObject> objects;
public MapObjects(Map map) {
this.map = map;
this.objects = new HashMap<>();
}
public void add(MapleMapObject object) {
objects.put(map.getObjectId(), object);
onAdd();
}
public void remove(MapleMapObject object) {
onRemove();
objects.remove(object.getObjectId());
}
protected abstract void onAdd();
protected abstract void onRemove();
}
I want to create an iterator so I can iterate over classes that extend from this class. For example, if I have a class named MapCharacters extends MapObjects<Character>
, I want to be able to do the following:
characters = new MapCharacters(this);
for (Character character : characters)
How can this be achieved?
If you just want to be able to iterate over objects
map, you can just call values()
on that and then create an iterator from that value set:
public abstract class MapObjects<MapleMapObject> implements Iterable<MapleMapObject> {
...
@Override public Iterator<MapleMapObject> iterator() {
return objects.values().iterator();
}
}
See more on this question at Stackoverflow