是否可以在Java中将类添加到数组中?

时间:2018-06-10 19:03:52

标签: java arrays

有没有办法将此代码压缩成数组?每个精灵对应一个先前已经声明过的单独的类。这是游戏的一部分,它从不同的类中收集精灵的x和y值。

private void doDrawing(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;

    g2d.drawImage(sprite.getImage(), sprite.getX(), 
        sprite.getY(), this);
    g2d.drawImage(sprite2.getImage(), sprite2.getX(), 
            sprite2.getY(), this);
    g2d.drawImage(sprite3.getImage(), sprite3.getX(), 
            sprite3.getY(), this);
    g2d.drawImage(sprite4.getImage(), sprite4.getX(), 
            sprite4.getY(), this);
    g2d.drawImage(sprite5.getImage(), sprite5.getX(), 
            sprite5.getY(), this);
    g2d.drawImage(sprite6.getImage(), sprite6.getX(), 
            sprite6.getY(), this);
    g2d.drawImage(sprite7.getImage(), sprite7.getX(), 
            sprite7.getY(), this);
    g2d.drawImage(sprite8.getImage(), sprite8.getX(), 
            sprite8.getY(), this);
    g2d.drawImage(sprite9.getImage(), sprite9.getX(), 
            sprite9.getY(), this);
    g2d.drawImage(sprite10.getImage(), sprite10.getX(), 
            sprite10.getY(), this);
    g2d.drawImage(sprite11.getImage(), sprite11.getX(), 
            sprite11.getY(), this);
    g2d.drawImage(sprite12.getImage(), sprite12.getX(), 
            sprite12.getY(), this);
    g2d.drawImage(sprite13.getImage(), sprite13.getX(), 
            sprite13.getY(), this);
    g2d.drawImage(sprite14.getImage(), sprite14.getX(), 
            sprite14.getY(), this);
    g2d.drawImage(sprite15.getImage(), sprite15.getX(), 
            sprite15.getY(), this);
}

2 个答案:

答案 0 :(得分:1)

你可以拥有一系列精灵:

MySptrite[] sprites = ...;
for (MySprite sprite : sprites) {
    g2d.drawImage(sprite.getImage(), sprite.getX(), sprite.getY(), this);
}

或者,更方便的是List

List<MySptrite> sprites = ...;
for (MySprite sprite : sprites) {
    g2d.drawImage(sprite.getImage(), sprite.getX(), sprite.getY(), this);
}

答案 1 :(得分:0)

public class Foo implements ImageObserver {

    private void doDrawing(Graphics g) {
        Sprite[] sprites = ...;
        Arrays.stream(sprites).forEach(sprite -> drawImage.accept((Graphics2D)g, sprite));
    }

    private final BiConsumer<Graphics2D, Sprite> drawImage = (g2d, sprite) -> g2d.drawImage(sprite.getImage(), sprite.getX(), sprite.getY(), this);
}