Guysont
Guysont

Reputation: 111

NullPointException and length of an array of objects

I'm having deep trouble when dealing with an array of objects. Basically what I have defined is the following:

public class PlayersList
{
private Player[] players;
private int length;
private int numPlayer = 0;
}

Which in this case players come from the data type players:

public class Player
{
public String UserName;

public Player(String UserName)
{
this.UserName = UserName;      
}
}

Now, when I try to invoke methods that involve traversing through an array of objects or the length of the object array, I get a NPE. I'm starting with a 3 member array, and I have already initialized all three members so that I don't get anything like that. However, if I then try to use something like:

  public Player findPlayer(String Player)
  {
    for(int i = 0; i < players.length; i++)
    {
      if(Player.equals(players[i].UserName))
      {
        return players[i];
      }
    }
    return null;
  }

And as well in other types of code involving an element of the player array or its length, I get a NPE. What I'm doing wrong? Is there any way to avoid this or could someone tell me what I'm missing? Thank you so much.

Edit: Here is the code for initializing players in the array:

 public PlayersList()
  {
    Player[] players = new Player[3];
    players[0] = new Player("Hi");
    players[1] = new Player("Bla");
    players[2] = new Player("Foo");
    length = 3;
  }

Upvotes: 1

Views: 56

Answers (2)

Radiodef
Radiodef

Reputation: 37845

Your players variable in the constructor is shadowing the field.

public class PlayersList
{
    private Player[] players;

    public PlayersList()
    {
        // shadows the field
        Player[] players = new Player[3];

        ...

Doing Player[] players in the constructor declares a new variable with the same name. Remove the type and it becomes an assignment to the field instead of a declaration:

    public PlayersList()
    {
        // now refers to the field
        players = new Player[3];

Upvotes: 1

Hakan Serce
Hakan Serce

Reputation: 11256

You are initializing a local array here

Player[] players = new Player[3];

Do this instead

players = new Player[3];

Upvotes: 1

Related Questions