Search code examples
javalistnullpointerexception

NullPointerException when adding to List


I am trying to iterate through a list of objects to figure out which ones are fighting each other. I am using the checkedGladiators list as something to compare against to prevent it from checking gladiators already assigned to a combat, as each s that isn't assigned already will build their entire combat around them. Currently I get a NullPointerException, so I used some test text to figure that it was happening right at listContains(checkedGladiators,s). I added the part before it. NOW the problem is happening between "Null" and "Null Changed" as well, which makes no sense to me.

for (Gladiator s : gladiators) {
    if (checkedGladiators == null) {
        System.out.println("Null");
        combat1.add(s);
        checkedGladiators.add(s);   
        System.out.println("Null Changed"); 
    }
    if (listContains(checkedGladiators, s)) { 
        // if gladiator is already in a combat do nothing
    } else { // if he isn't

    }
}

listContains class:

public boolean listContains(List<Gladiator> List, Gladiator search) {
    for (Gladiator p : List) {
        if (p.equals(search)) {
        return true;
        }
    }
    return false;
}

Does anyone know why this would occur? Thanks

Edit1:

public class Ai {
private List<Gladiator> gladiators;
private List<List<Gladiator>> combatsList;
private List<Gladiator> checkedGladiators;
private List<Gladiator> combat1;
private List<Gladiator> combat2;
private List<Gladiator> combat3;
private List<Gladiator> combat4;
private List<Gladiator> combat5;
private List<Gladiator> combat6;    
private List<Gladiator> combat7;    
private List<Gladiator> combat8;    
private List<Gladiator> guardList;
private List<Gladiator> advanceList;
private List<Gladiator> retreatList;
int totalCombats = 0; // total combats going on

I have initialized the list variable in the class already.


Solution

  • You are forgetting to create the checkedGladiators object.

    So, create the object before your loop as:

    List<Gladiators> checkGladiators = new ArrayList<Gladiators>();

    Then, in your loop, rather than testing for checkGladiators == null...

    test for checkGladiators.isEmpty().