I am wondering whether I should initialize an ArrayList inside a constructor or outside, as demonstrated below. Is there any difference between the two ways or if not, what do you think is the most common/best way of doing it in the industry?
Initializing the variable inside the constructor:
public class Customer {
private String name;
private ArrayList<Double> transactions;
public Customer(String name, double initialAmount) {
this.name = name;
this.transactions = new ArrayList<Double>();
}
public void addTransaction(double amount) {
this.transactions.add(amount); // autoboxing
}
}
vs outside:
public class Customer {
private String name;
private ArrayList<Double> transactions = new ArrayList<Double>();
public Customer(String name, double initialAmount) {
this.name = name;
}
public void addTransaction(double amount) {
this.transactions.add(amount); // autoboxing
}
}