实例变量部分中的Java ArrayList add()方法 [英] Java ArrayList add() method in the instance variable section

查看:347
本文介绍了实例变量部分中的Java ArrayList add()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在通常声明/定义实例变量的Java类中,我希望将 ArrayList 作为实例变量之一,并使用一些元素初始化它出去。一种方法是声明 ArrayList 并在构造函数中初始化它。但是,我想知道为什么初始化构造函数之外的值是非法的。例如,

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.

在类构造函数中:

public class Test {
    // some instance variables...

    private List<String> list = new ArrayList<>();

    public Test() {
        list.add("asdf");
    }
    // methods here...
}

在类初始化块中:

public class Test {
    // some instance variables...

    private List<String> list = new ArrayList<>();

    {
        list.add("asdf");
    }
    // methods here...
}

更多信息:

  • What's the difference between an instance initializer and a constructor?

这篇关于实例变量部分中的Java ArrayList add()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆