将不同对象类型的数组列表合并为一个

Combining arraylists of different object types into one

我有一些数组列表,其中包含基于 class 中的构造函数的对象(用于类似绘画的程序),并希望将它们全部放在同一个数组列表中,而不是让每个项目按顺序重绘。

我尝试将数组转换为二维数组(未成功),还尝试将标识符附加到每个对象并将我从基本数组返回的内容打印到控制台,package1.package2.ShapeClas@<string of letters and numbers>未成功获取 returns 我可以做任何事情。

我想合并的问题数组与下面类似

public static ArrayList<ShapeClass> emptyRectangle = new ArrayList<ShapeClass>();
public static ArrayList<ShapeClass> filledRectangles = new ArrayList<ShapeClass>();
public static ArrayList<ShapeClass> lineArray = new ArrayList<ShapeClass>();

随着每个数组都由沿线创建的对象填充(如果这还不够,可以共享一些其他帮助),形状的比例随着 windows 的大小而变化关于重新缩放

for (ShapeClass cr : emptyRectangle) {
            g.setColor(cr.getForeground());
            Rectangle2D r = cr.getRectangle();
            Graphics2D g2 = (Graphics2D) g;
            g2.draw(new Rectangle2D.Double(r.getX() * JPanel1.getWidth(), r.getY() 
                    * JPanel1.getHeight(),r.getWidth() * JPanel1.getWidth(), 
                    r.getHeight() * JPanel1.getHeight()));
        }

我希望能够将数组组合成一个数组,这样我就可以按顺序重新绘制每个元素,因为现在它们是按形状类型绘制的,因此一种形状类型总是与另一种形状类型重叠。我如何将它们放入单个数组并成功确定要绘制的形状?

由于 ArrayList class 实现了 List 接口,您只需使用 List 接口中的 .addAll(Collection c) 方法即可轻松实现。

ArrayList<ShapeClass> allShape = new ArrayList<>();    
allShape.addAll(emptyRectangle);
allShape.addAll(filledRectangles);
allShape.addAll(lineArray);

编辑:

方法 1: 您无权访问形状Class

当一个对象被添加到一个集合(扩展泛型类型)时,实际的 class 对象不会被改变。您可以使用 .getClass() 方法取回它的 class 。但是,在调用其方法之前必须将其转换回其原始形式。

    for(ShapeClass shape: allShapes) {
        System.out.println(shape.getClass()); // class <actual class>
        if(shape instanceof Triangle) {
            Triangle tri = (Triangle) shape;
            tri.paint();
        } else if(shape instanceof Rectangle) {
            Rectangle rec = (Rectangle) shape;
            rec.paint();
        }
    }

方法 2(更好):您可以访问 ShapeClass(动态绑定)

如果您可以访问通用 Class(即 ShapeClass),将更容易实现相同的目的。在这种情况下,您只需在 ShapeClass 中定义一个方法 paint(),并在子 class 中覆盖它(例如 Rectangle)。

方法调用在Java中动态绑定。所以JVM会检查实际类型并为你调用最具体的方法

    ArrayList<ShapeClass> allShape = new ArrayList<>();
    allShape.addAll(emptyRectangle);
    allShape.addAll(filledRectangles);
    allShape.addAll(lineArray);

    for(ShapeClass shape: allShape) {
        shape.paint();   // make sure you have a paint() method in the ShapeClass, and it is overriden in the subclass. 
    }