Search code examples
javaarraysarraylistgraphics2d

ArrayList of Shapes


I have some problem with my code. I want to write program which paints Rectangle, Circle and one more shape created from points. I want to use Graphics2D and here is my question: How to make one ArrayList of all this shapes? Is it even possible? I made sth like this:

List<Shape> shapesArray = new ArrayList<Shape>();
shapesArray.add(new Rectangle2D.Double());
shapesArray.get(0).setFrameFromDiagonal(point_a, point_b)


When i do it like that i can't use Rectangle2D methods.

Thanks for help


Solution

  • You can for sure do this:

    List<Shape> shapesArray = new ArrayList<Shape>();
    shapesArray.add(new Rectangle2D.Double());
    shapesArray.get(0).setFrameFromDiagonal(point_a, point_b)
    

    but to call specific class methods a cast is required... to be sure if a shape in the list can be cast you need to check the instance

    like:

    if(shapesArray.get(0) instanceof Rectangle2D){
          ((Rectangle2D)shapesArray.get(0)).setFrameFromDiagonal(point_a, point_b)
    }