为什么我的构造函数不起作用?(JAVA)

ML.*_*ML. 2 java oop selenium constructor

我有以下类实现

public class PublisherHashMap
{
     private static HashMap<Integer, String> x;

     public PublisherHashMap()
     {
         x.put(0, "www.stackoverflow.com");
     }
}
Run Code Online (Sandbox Code Playgroud)

在我的测试函数中,由于某种原因,我无法创建对象.

@Test
void test()
{ 
   runTest();
}

public static void runTest()
{
    PublisherHashMap y = new PublisherHashMap();
}
Run Code Online (Sandbox Code Playgroud)

编辑:我没有构建HashMap.

And*_*lko 7

在构建x私有HashMap之前,您正试图使用它.因此,您需要先构建它.您可以通过以下任何方式执行此操作:

1)在构造函数中:

x = new HashMap<Integer, String>(); 
// or diamond type  
x = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)

2)在班级中作为这个班级的一个领域:

private static HashMap<Integer, String> x = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)

3)在初始化块中:

static { 
    x = new HashMap<>();
}
// or the no-static block
{
    x = = new HashMap<>();
}
Run Code Online (Sandbox Code Playgroud)