initializing ArrayList<>() in methods or constructor

Y Sang picture Y Sang · Feb 16, 2018 · Viewed 11.1k times · Source
import java.util.ArrayList;
public class Team {  

    private String name;
    private ArrayList<Player> team;

    public Team(String name)    {
        this.name = name;
        //how come i have to initialize it here in the constructor to see the full list?          
        this.team = new ArrayList<Player>();
    }

    public void addPlayer(Player player)    {
        //why can't i initialize it here in the method, this gives me a list of only recent add?
        //this.team = new ArrayList<Player>(); 
        this.team.add(player);
    }

    public void printPlayers()  {            
        for(Player players : this.team) {
            System.out.println(players);
        }
    }
    public String getName() { return this.name; }
}
  • I'm trying to figure out why this.team = new ArrayList<Player>() have to be in the constructor?
  • Why can't I have this.team = new ArrayList<Player>() initialized in the method?
  • I know that when I run it with the code in the constructor it works as intended (it gives me the full list when things are added)
  • BUT when it's initialized in the method it only list the last given addition to the list. Is it wrong to have it initialized in the method?
  • Also what's the difference of having it initialized as private ArrayList<Player> team = new ArrayList<Player>(); before the constructor?

Answer

Andy Turner picture Andy Turner · Feb 16, 2018

Answering just the question:

Also what's the difference of having it initialized as private ArrayList<Player> team = new ArrayList<Player>(); before the constructor?

Nothing, aside from the fact that team would be initialized before name.

Field initializers are syntactic sugar for instance initializers. So this:

private ArrayList<Player> team = new ArrayList<Player>();

is identical to this:

private ArrayList<Player> team;

{
  // This is an instance initializer.
  team = new ArrayList<Player>();
}

and instance initializers are gathered together and inserted into every constructor which invokes (implicitly or explicily) super, in between the call to super and the rest of the constructor body. So this:

public class Team {  

    private ArrayList<Player> team = new ArrayList<>();

    public Team(String name)    {
      this.name = name;
    }
}

is identical to:

public class Team {  

    private ArrayList<Player> team;

    public Team(String name)    {
      super();

      this.team = new ArrayList<>();

      this.name = name;
    }
}