简体   繁体   中英

When an object has multiple internal collections, how can i iterate over them from the outside?

a while ago i wrote an editor for a navigation graph that represented the paths inside (and between) buildings. it was stored inside a Graph-class.

the edges, for example were stored in one collection per floor, plus one collection for the ones that were between floors.

to draw them (only the current floor) or save them to disk (all of them), i needed to get at them from the outside. for that i implemented methods like callWithAllEdges and callWithAllEdgesIn, the latter taking a parameter to specify a floor.

those methods took a functor (at least i called it that), that was then called with the edges.

this is what drawing the edges of one floor looked like:

graph.callWithAllEdgesIn(id, new Functor<Edge>() {
    public void call(Edge e) {
        drawEdge(g,e);
    }
});

this is a bit long-winded, of course. might be a problem with java and not with my solution though, i dont know.

another way would have been to just make a method that puts references to all the needed edges into a new collection and then iterate over that, i guess. seemed kind of wrong to me though.

my question is: how could i have solved that better?

Your current design is perfectly reasonable. Another option is to provide an Iterable/Iterator. That way you don't need to copy everything into a new list, but can instead lazily step through your internal lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM