【发布时间】:2016-04-28 20:57:46
【问题描述】:
我想创建一个包含数组的 ArrayList 并调用该数组内对象的函数。
我正在尝试在数组中调用函数 display(),但即使数组包含一个对象,我也会得到 NPE。
这是我的代码:
class Ball
{
int x;
int y;
int size;
color c;
Ball()
{
x = int (random(width));
y = int (random(height));
size = int (random(100));
c = color(random(255));
}
void display()
{
fill(c);
ellipse(x,y,size,size);
}
}
ArrayList<Ball[]> balls;
void setup()
{
size(500,500);
balls = new ArrayList<Ball[]>();
for( int i = 0; i < 1; i++)
{
balls.add(new Ball[2]);
println(balls);
}
}
void draw()
{
background(255);
for( int i = 0; i < 1; i++)
{
Ball[] b = balls.get(i);
b[i].display();
}
}
有人知道怎么做吗?
【问题讨论】:
-
balls.get(0)[0].display()可以工作 -
你的问题是你没有创建任何 Balls - 只有一个空数组。
-
数组为空。你没有创造任何球。
-
数组不包含非空对象引用。即使您清楚地声明它是用英语执行的,但您并没有在 Java 中强制执行。由于编译器只对 Java 源代码做出反应,因此您需要在代码中反映您的断言。
标签: java arrays arraylist processing