在Java构造函数中添加"this"对Array的引用失败

jan*_*jan 0 java constructor

我绝对无能为力,为什么以下代码不断抛出NullpointerExceptions.我无法理解或调试它(从较大的类中删除它的代码)...

代码基于"枚举模式",我想保留类中包含的所有"常量"的列表/映射(我可能正在使用Reflection,但使用List/Map更容易... )

   public class Country {

        public static final Country SWITZERLAND = new Country("SWITZERLAND");

        private static ArrayList<Country> countries = new ArrayList<Country>();

        private  Country(String constname) {     
             //constname is currently not used (I will use it for a Key in a Map)
            System.out.println(constname);
            System.out.println("Ref debug:"+this);

            //Ad this to the Countries
            Country.countries.add(this);
        }
    }
Run Code Online (Sandbox Code Playgroud)

非常感谢帮助.我在这里错过了什么?

Kon*_*lph 5

SWITZERLAND是静态的,之前 可能是初始化的countries,也是static.因此,countries仍然null在构造函数中调用SWITZERLAND.

要强制定义良好的初始化顺序,请使用static块:

public class Country {

    public static final Country SWITZERLAND;

    private static ArrayList<Country> countries;

    static {
        countries = new ArrayList<Country>();
        SWITZERLAND = new Country("SWITZERLAND");
    }
}
Run Code Online (Sandbox Code Playgroud)