Java ArrayList无法解析变量类型
试图获取名为DrawGraphics的自定义类,以包含自定义对象的ArrayList,而不是单个精灵。但是ArrayList拒绝接受新的Bouncer对象,当它接受时,DrawGraphics类的其余部分不会识别它 原始代码Java ArrayList无法解析变量类型,java,arraylist,Java,Arraylist,试图获取名为DrawGraphics的自定义类,以包含自定义对象的ArrayList,而不是单个精灵。但是ArrayList拒绝接受新的Bouncer对象,当它接受时,DrawGraphics类的其余部分不会识别它 原始代码 package objectssequel; import java.util.ArrayList; import java.awt.Color; import java.awt.Graphics; public class DrawGraphics { Bou
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>();
这生成了“令牌上的语法错误、构造错位”和“令牌上的语法错误”movingSprite,此令牌后应为VariableDeclaratorId”编译器错误。我猜这可能是因为我在方法体之外使用了bouncerList.add(),所以我为类DrawGraphics创建了以下方法
public void addBouncer(Bouncer newBouncer) {
bouncerList.add(newBouncer);
}
然后,我在DrawGraphics()中使用以下命令调用了此方法:
编译器错误通知我无法将movingSprite解析为变量类型。我试图这样做:
public void addBouncer() {
Bouncer movingSprite;
bouncerList.add(movingSprite);
}
然后尝试通过给movingSprite一个null设置来初始化它,但也没有这样的运气,可能还有十几种其他的组合方法来解决这个问题。有什么解决办法吗?如何在DrawGraphics类中创建Bouncer对象的ArrayList
编辑:是否可以不使用并从原始代码中删除“Bouncer movingSprite”,而仅从bouncerList.add()创建对象的实例?在该代码中
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);
召唤
您正试图在对象构造时声明并初始化数组?遗憾的是,java集合使这个看似显而易见的用例变得笨拙
List< Bouncer > bouncerList = new ArrayList< Bouncer >() { {
add( new Bouncer() );
} };
ListbouncerList=newarraylist(){{
添加(新弹跳器());
} };
如果有必要,这可能会导致序列化DrawGraphics类的困难。为什么不在DrawGraphics构造函数中填充它
另一种选择:
List< Bouncer > bouncerList = new ArrayList< Bouncer >( Arrays.asList( new Bouncer() ) );
ListbouncerList=newarraylist(Arrays.asList(new Bouncer());
您还可以使用guava的Lists实用程序类在一行中构造和填充数组列表。Ahh是的,输入我的问题时有误。我有保镖名单,加上(新保镖)。在移动向量完成后调用addBouncer(movingSprite),但是有没有其他方法来创建数组列表、添加对象并删除原始代码中的原始“Bouncer movingSprite”?调用
bouncerList.remove(oldBouncer)
我的措词不好。我的意思是,我可以不使用原始的“Bouncer movingSprite;”创建数组列表对象吗首先编码?您可以,但您正在使用draw
方法中的movingSprite
。那是从哪里来的?
addBouncer (movingSprite);
List< Bouncer > bouncerList = new ArrayList< Bouncer >() { {
add( new Bouncer() );
} };
List< Bouncer > bouncerList = new ArrayList< Bouncer >( Arrays.asList( new Bouncer() ) );