recursion - Java - alternative to instanceof? -
i have shape superclass , nestedshape subclass. nestedshape subclass has arraylist ('shapeslist') of shapes nested within it. need implement 'contains' method nestedshape. method, when given shape object, should check whether shape exists in nestedshape's shapelist. implementation @ moment simple: call arraylist .contains() method on shapeslist.
however, 'contains' method need implement has check nestedshape in shapeslist, shape's shapelist doesn't contain shape being searched for. obvious way me of doing use instanceof check if each shape in shapelist nestedshape. then, guess i'd recursively call 'contains' method on if nestedshape. however, i'm not sure if way of doing - i've heard use of instanceof frowned upon (also, i'm not sure if idea of using recursion work).
could suggest better way of solving problem?
thanks :)
use polymorphism:
public class shape { public boolean contains(shape shape) { return false; } } public class nestedshape extends shape { private list<shape> subshapes = new arraylist<shape>(); @override public boolean contains(shape shape) { if (subshapes.contains(shape)) { return true; } (shape subshape : subshapes) { if (subshape.contains(shape)) { return true; } } return false; } }
Comments
Post a Comment