我有以下类实现
public class PublisherHashMap
{
private static HashMap<Integer, String> x;
public PublisherHashMap()
{
x.put(0, "www.stackoverflow.com");
}
}
在我的测试函数中,由于某种原因我无法创建对象。
@Test
void test()
{
runTest();
}
public static void runTest()
{
PublisherHashMap y = new PublisherHashMap();
}
编辑:我没有构造 HashMap。
最佳答案
您正在尝试在构造私有(private)HashMap
之前使用x
。因此,您需要首先构建它。您可以通过以下任一方式执行此操作:
1)在构造函数中:
x = new HashMap<Integer, String>();
// or diamond type
x = new HashMap<>();
2)在类中作为该类的字段:
private static HashMap<Integer, String> x = new HashMap<>();
3) 在初始化 block 中:
static {
x = new HashMap<>();
}
// or the no-static block
{
x = = new HashMap<>();
}
关于java - 为什么我的构造函数不工作? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31839859/