如何在 java 中创建 ArrayList <Shape> 的对象

How do I create an object of an ArrayList <Shape> in java

我想创建一个 ShapeArrayList 的新对象。 ArrayList 包含形状、矩形、椭圆等... ArrayList<Shape> shapes = new ArrayList<Shape>(); 新对象必须包含它拥有的形状和一个文本属性来命名形状。这就是我想要实现的目标:

我该怎么做?

已编辑

我想说的是

我到了!现在我想 java 把它写成 "Student is linked to ID"

public class NamedShape {
    private String name;
    private Shape shape;
    public NamedShape( String name, Shape shape ){
        this.name = name;
        this.shape = shape;
    }
    public String getName(){ return name; }
    public Shape getShape(){ return shape; }
}

现在你可以创建List<NamedShape>等等

List<NamedShape> shapes = new ArrayList<>();
shapes.add( new NamedShape( "Humpty-Dumpty",
                            new Ellipse2D.Double( x, y, w, h ) ) );
shapes.add( new NamedShape( "John Doe",
                            new Rectangle2D.Double( u, v, a, b ) ) );

或者您遍历您拥有的 List<Shape> 并添加名称:

for( Shape shape: myUnnamedShapes ){
    shapes.add( new NamedShape( inventName(), shape ) );
}

以后去画画,

for (NamedShape s : shapes) { 
    graphSettings.setPaint(strokeCounter.next()); 
    graphSettings.draw(s.getShape()); 
}

1.创建接口Shape -

interface Shape {

}  

2. 现在每个形状 - 矩形,椭圆等都可以实现 Shape 接口 -

Rectangle implements Shape{
 String name;
 // other properties as required

  //constructor as your requirement
  //getters setters as your requirement
}

或者 -

Ellipse implements Shape{
     String name;
     // other properties as required

     //constructor as your requirement
     //getters setters as your requirement

    }

3. 现在创建一个 ArrayListShape -

ArrayList<Shape> shapes = new ArrayList<Shape>)();

由于 RectangleEllipse 都实现了 Shape,因此 ArrayList 形状可以容纳这两种类型的对象。之后你可以写 -

Rectangle r = new Rectangle();
Ellipse e = new Ellipse();
shapes.add(r);
shapes.add(e);  

希望对您有所帮助。
非常感谢。