我想创建一个包含数组的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();
}
}
有人知道怎么做吗?
最佳答案
您有一个空 Ball
数组列表。创建(空)数组后添加球:
void setup()
{
size(500,500);
balls = new ArrayList<Ball[]>();
for( int i = 0; i < 1; i++)
{
Ball[] ballsArray = new Ball[2];
ballsArray[0] = new Ball();
ballsArray[1] = new Ball();
balls.add(ballsArray);
println(balls);
}
}
关于java - 如何调用ArrayList中的Array函数? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36925334/