【发布时间】:2017-07-28 22:15:28
【问题描述】:
我有一个类,其中包含一些 ArrayList 的 BufferedImage,但我遇到了一个严重的问题。有两种可能:
- ArrayList 都是静态的,因此它们的获取方法是:这工作正常,因为应用程序正在启动并且动画正在完美运行。但我不能有不同的动画,因为有静态。
-ArrayList(和它们的 getter)不是静态的:当 getDown() 被调用时,我得到一个 NullPointerException,它指向调用这个的精确时刻。
在此之前,我使用简单的数组,我认为使用 ArrayLists 可以解决问题,但没有区别。
我不明白为什么会这样,你能帮我解决这个问题吗?
public class AnimUnit {
private static final int width = 32, height = 32, nbframe = 4;
private ArrayList<BufferedImage> down;
private ArrayList<BufferedImage> up;
private ArrayList<BufferedImage> right;
private ArrayList<BufferedImage> left;
private ArrayList<BufferedImage> idle;
public AnimUnit(SpriteSheet sheet) {
this.down = new ArrayList<BufferedImage>();
this.up = new ArrayList<BufferedImage>();
this.left = new ArrayList<BufferedImage>();
this.right = new ArrayList<BufferedImage>();
this.idle = new ArrayList<BufferedImage>();
for(int i = 0; i < nbframe; i++)
down.add(sheet.crop((width*2)+2, (height*i)+i, width, height));
for(int i = 0; i < nbframe; i++)
up.add(sheet.crop((width*3)+3, (height*i)+i, width, height));
for(int i = 0; i < nbframe; i++)
left.add(sheet.crop((width)+1, (height*i)+i, width, height));
for(int i = 0; i < nbframe; i++)
right.add(sheet.crop((width*4)+4, (height*i)+i, width, height));
for(int i = 1; i < nbframe; i++)
idle.add(sheet.crop(0, (height*i)+i, width, height));
}
public static int getWidth() {
return width;
}
public static int getHeight() {
return height;
}
public ArrayList<BufferedImage> getDown() {
return down;
}
public ArrayList<BufferedImage> getUp() {
return up;
}
public ArrayList<BufferedImage> getRight() {
return right;
}
public ArrayList<BufferedImage> getLeft() {
return left;
}
public ArrayList<BufferedImage> getIdle() {
return idle;
}
【问题讨论】:
-
可以分享
AnimUnit的客户端代码调用方法吗?通常,在面向对象编程中应避免使用static方法/成员。您应该改为使用对象实例。 -
我建议使用单例模式而不是静态方法来“随机”类方法访问。
-
我从代码中删除了“静态”,因为似乎人们误解了我的观点。我希望我的代码与实例一起正常运行,但如果它们不是静态的,它会不断给我 NullPointerException,这对我来说很奇怪。我没有找到解决问题的方法...
-
很多人考虑singletonsananti-pattern
标签: java arraylist nullpointerexception static bufferedimage