1

For some reason this function in my project is failing:

public void SetPlayersLineups(HashMap<Integer, Player> _players, 
    ArrayList<Integer> _lineup, boolean isAwayTeam) {

    System.out.println(_players.get(2)); //works properly
    System.out.println(_players.get(2).getNumberHits()); //null pointer exception

    if (isAwayTeam) {
        this.awayLineup = _lineup;
        this.awayPlay = _players;
    } else {
        this.homeLineup = _lineup;
        this.homePlay = _players;
    }

}

/* from Player class */

public int getNumberHits() {

    return this.hits;

}

I have a Player class, with a member get function getNumberHits(). The this.awayPlay and this.homePlay properties are not being set correctly. So I debugged with the System.out.println statements. The first returns a Player instance correctly. But when I call the get function I get a null pointer exception. Any ideas?

3 Answers 3

2

Ok, one thing at a time. First off, you're printing _players.get(2).getNumberHits() and getting a NPE. Either _players.get(2) returns null, or getNumberHits() does something that throws an NPE. What cannot be the case is that _players2 is null since you already said that worked.

So, you need to look into what's wrong with the object _players you are being passed. I would suggest you try setting a breakpoint and analysing the object with your IDE (e.g. Eclipse or Netbeans)

Sign up to request clarification or add additional context in comments.

Comments

1

If hits is declared as an Integer and is null, this method:

Integer hits; // default value of objects is null

public int getNumberHits() {
    return hits;    
}

will throw an NPE due to auto unboxing, because the method actually compiles as:

public int getNumberHits() {
    return hits.intValue();    
}

Either assign a value to hits:

Integer hits = 0;

or give hits the type of int, whose default value is 0, not null:

int hits;

1 Comment

I have hits assigned as an integer property declaration: private int hits = 0;
0

The problem is that hits is null, and Java tries to autobox hits (which is Integer) to int, and produces NullPointerException

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.