我想创建一个ArrayList
Shape
的新对象。 ArrayList
包含形状,矩形,椭圆等... ArrayList<Shape> shapes = new ArrayList<Shape>();
新对象必须包含它所包含的形状以及用于命名形状的文本属性。这就是我想要实现的目标:
我该怎么做?
EDITED
这就是我想说的
我到达了这里!现在我希望java把它写成&#34;学生与ID&#34;
相关联
答案 0 :(得分:3)
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。现在创建ArrayList
Shape
-
ArrayList<Shape> shapes = new ArrayList<Shape>)();
由于Rectangle
和Ellipse
都实现Shape
,ArrayList
形状可以包含两种类型的对象。之后你可以写 -
Rectangle r = new Rectangle();
Ellipse e = new Ellipse();
shapes.add(r);
shapes.add(e);
希望它会有所帮助 非常感谢。
答案 1 :(得分:1)
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());
}