Question

I have a Shape superclass and a NestedShape subclass. The NestedShape subclass has an ArrayList ('ShapesList') of Shapes that are nested within it. I need to implement a 'contains' method for NestedShape. This method, when given a Shape object, should check whether the shape exists in the NestedShape's ShapeList. My implementation at the moment is very simple: just call the ArrayList .contains() method on ShapesList.

However, the 'contains' method I need to implement also has to check that for any NestedShape in the ShapesList, that shape's ShapeList also doesn't contain the shape that is being searched for. The obvious way to me of doing this is to use instanceof to check if each Shape in the ShapeList is a NestedShape. Then, I guess I'd recursively call my 'contains' method on it if it was a NestedShape. However, I'm not sure if this is a good way of doing this - I've heard that the use of instanceof is frowned upon (also, I'm not sure if my idea of using recursion would even work).

Could anyone suggest a better way of solving this problem?

Thanks :)

Était-ce utile?

La solution

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;
        }
        for (Shape subShape : subShapes) {
            if (subShape.contains(shape)) {
                return true;
            }
        }
        return false;
    }
}

Autres conseils

Two ideas:

  1. Don't let NestedShape extend Shape, but handle them seperately.

  2. Let all Shapes be 'nested'. With single shapes returning always false for contains().

If

  • the performance of the contains() method is your concern and
  • NestedShape are immutable meaning the list of nested Shape instances once set will never change

then I would suggest a slightly different approach.

Instead of recursively iterating though all the NestedShapes you can add a Set inside the Shape class that will store the references to all the NestedShape instances for which it is possible to access this Shape instance.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top