In a Java class where you normally declare/define instance variables, I would like to have an ArrayList as one of the instance variables and initialize it with some elements to start out with. One way of doing this is declare the ArrayList and initialize it in a constructor. However, I am wondering why it is illegal to initialize the value outside the constructor. For example,
public class Test {
// some instance variables...
private ArrayList<String> list = new ArrayList<String>();
list.add("asdf");
// methods here...
}
So I get that this is illegal. But why exactly is this illegal?
You cannot execute statements freely in a class. They should be inside a method. I recommend you to add this line in the constructor of the class or in a class initialization block.
In class constructor:
public class Test {
// some instance variables...
private List<String> list = new ArrayList<>();
public Test() {
list.add("asdf");
}
// methods here...
}
In class initialization block:
public class Test {
// some instance variables...
private List<String> list = new ArrayList<>();
{
list.add("asdf");
}
// methods here...
}
More info:
It is illegal, because initializing fields is exactly the reason, why constructors exist!
In Java, it is not possible to have code anywhere 'outside' of a method or constructor (or class-initializer). It is possible to have simple expressions in a field initializer, but not multiple statements:
public class Test {
// here, at class level, you can only declare fields, methods or constructors!
// But you cannot have procedural code!!!
// field without initializer (=> default initialization with null)
private List<String> list1;
// field with explicit initializer expression
private List<String> list2 = new ArrayList<String>();
public Test() {
// initialize fields
this.list1 = new ArrayList<>();
this.list2.add("asdf");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With