Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList add() method in the instance variable section

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?

like image 477
jkim796 Avatar asked Sep 27 '26 08:09

jkim796


2 Answers

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:

  • What's the difference between an instance initializer and a constructor?
like image 200
Luiggi Mendoza Avatar answered Sep 30 '26 13:09

Luiggi Mendoza


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");
    }
}
like image 28
isnot2bad Avatar answered Sep 30 '26 15:09

isnot2bad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!