Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an iterator in Java

Tags:

java

iterator

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?

like image 597
Gilbert Williams Avatar asked Jan 07 '23 14:01

Gilbert Williams


1 Answers

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();
    }
}
like image 59
Jon Skeet Avatar answered Jan 17 '23 02:01

Jon Skeet