尝试获取一个名为DrawGraphics的自定义类,以包含自定义对象的ArrayList而不是单个Sprite。然而,ArrayList拒绝接受新的Bouncer对象,并且当它执行时,DrawGraphics类的其余部分无法识别它。
原始代码
package objectssequel;
import java.util.ArrayList;
import java.awt.Color;
import java.awt.Graphics;
public class DrawGraphics {
Bouncer movingSprite; //this was the original single sprite
/** Initializes this class for drawing. */
public DrawGraphics() {
Rectangle box = new Rectangle(15, 20, Color.RED);
movingSprite = new Bouncer(100, 170, box);
movingSprite.setMovementVector(3, 1);
}
/** Draw the contents of the window on surface. */
public void draw(Graphics surface) {
movingSprite.draw(surface);
}
}
尝试解决方案: 首先,我创建了Bouncer类的对象的ArrayList
ArrayList<Bouncer> bouncerList = new ArrayList<Bouncer>();
一切都好。我首先在此
下面的行中插入以下代码bouncerList.add(movingSprite);
这会在令牌上产生&#34;语法错误,错误放置的构造&#34;和&#34;令牌上的语法错误&#34; movingSprite&#34;,此令牌后的VariableDeclaratorId&#34;编译器错误。我猜这可能是因为我在方法体外使用了bouncerList.add(),所以我为DrawGraphics类创建了以下方法
public void addBouncer(Bouncer newBouncer) {
bouncerList.add(newBouncer);
}
然后我在DrawGraphics()中使用:
调用此方法addBouncer(movingSprite);
编译器错误告诉我,movingSprite无法解析为变量类型。我试过这个:
public void addBouncer() {
Bouncer movingSprite;
bouncerList.add(movingSprite);
}
然后尝试初始化movingSprite,给它一个null设置,也没有这样的运气,可能还有十几个其他组合方法来解决这个问题。有解决方案吗如何在DrawGraphics类中创建Bouncer对象的ArrayList?
编辑:是否可以不使用和删除&#39; Bouncer movingSprite&#39;从原始代码创建一个对象的实例只是从bouncerList.add()?
答案 0 :(得分:1)
在此代码中
public void addBouncer(Bouncer newBouncer) {
bouncerList.add(Bouncer); // this is trying to add a class
}
您需要更改为
public void addBouncer(Bouncer newBouncer) {
bouncerList.add(newBouncer); // this will add the object
}
之后
movingSprite.setMovementVector(3, 1);
呼叫
addBouncer (movingSprite);
答案 1 :(得分:0)
您是否尝试在对象构建时声明并初始化数组?遗憾的是,java集合使这个看似明显的用例变得尴尬。
List< Bouncer > bouncerList = new ArrayList< Bouncer >() { {
add( new Bouncer() );
} };
如果有必要,这可能会导致难以序列化DrawGraphics类。为什么不在DrawGraphics构造函数中填充它?
另一种选择:
List< Bouncer > bouncerList = new ArrayList< Bouncer >( Arrays.asList( new Bouncer() ) );
您还可以使用guava的Lists实用程序类在一行中构造和填充数组列表。