I have a game with some asteroid objects in an arraylist. To keep my code neat and tighty-ish, I want to pass this arraylist to different classes/methods. I thought I had it figured out.. but apparently not. Here goes: My Level1 class starts by an initializing method (init) that calls the populateAsteroid method in the asteroid class. The Level1 class furthermore contains an update function that loops through the asteroid arraylist and updates it. All of this works fine:
public class Level1 {
private Asteroid populateAsteroid
private Collision collision;
public void init() {
populateAsteroid = new Asteroid();
// create and populate an arraylist with asteroid objects
populateAsteroid.populateAsteroid(1);
collision = new Collision();
}
public void update() {
// get the arraylist
ArrayList<Asteroid> asteroidList = populateAsteroid.getAsteroidList();
for(int i = 0; i < asteroidList.size(); i++) {
Asteroid a = asteroidList.get(i);
a.update(i);
}
collision.checkCollision();
}
}
public class Asteroid {
public ArrayList<Asteroid> asteroidList;
public void populateAsteroid(int level) {
// if the arraylist is null, as when the function is called by init, create the array
if (asteroidList == null){
asteroidList = new ArrayList<Asteroid>();
}
for (int i = 1 + asteroidList.size(); i <= (asteroidsAtEachLevel[level]); i++){
Asteroid a = new Asteroid();
asteroidList.add(a);
}
}
public ArrayList<Asteroid> getAsteroidList() {
return asteroidList;
}
}
However, the trouble comes in my collision class, called by the update function in the Level1 class, which contains the checkCollision method
public class Collision {
private Asteroid a;
public void checkCollision(){
a = new Asteroid();
// get the arraylist
ArrayList<Asteroid> asteroidList = a.getAsteroidList();
if (asteroidList == null){
System.out.println("null");}
}
..."more code"....
The list is null, even though I believe I am retrieving the arraylist identically to the way I do it in the Level1.update function. Is it because the arraylist is some how not visible as it is created from a call in the Level1 class? Any suggestions?
populateAsteroidona, so the list never gets created.null. Did you perhaps mean to use the one you created back in yourinit()method, instead creating a new (empty) one incheckCollision()?a = new Asteroid();and then callinga.getAsteroidList();, This is not initializing the asteroidlistasteroidListstatic or you create another class, likeAsteroidHandlerwhich manages the list of asteroids. Then you need to pass that handler instance tocheckCollision.