I'm trying to figure out why this.team = new ArrayList() have to be in the constructor?
It doesn't, it has to be initialized before it is used. You can initialize it anywhere you want as long as you don't call printPlayer() or addPlayer() before.
Why can't I have this.team = new ArrayList() initialized in the method?
You actually can. See this example:
public void addPlayer(Player player) {
if (team == null) {
team = new ArrayList();
}
team.add(player);
}
public void printPlayers() {
if (team != null) {
for (Player p : team) {
System.out.println(p);
}
}
}
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?
No, it's not wrong. It's typically referred to as "lazy initialization" or "on demand" if you do it in the way of the example above.
Also what's the difference of having it initialized as private ArrayList team = new ArrayList(); before the constructor?
Not much, the difference lies in when it is initialized.
public class Example {
public static List<T> myList = new ArrayList<T>(); // this is done first
public static List<T> aList;
public List<T> someList;
static {
// this is also done first (on class load)
aList = new ArrayList<T>();
}
{
// this is done right before the constructor (I believe)
// it is called an 'initialization block'
someList = new ArrayList<T>();
}
public Example() {
// this one you already know...
}
}