【问题标题】:How to call function of an Array in ArrayList? Java如何在 ArrayList 中调用数组的函数?爪哇
【发布时间】: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


【解决方案1】:

您有一个 empty 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);
  }
}

【讨论】:

    猜你喜欢
    • 2015-06-07
    • 1970-01-01
    • 2021-03-11
    • 2022-11-18
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 2021-09-29
    相关资源
    最近更新 更多