I have the following class implementation
public class PublisherHashMap
{
private static HashMap<Integer, String> x;
public PublisherHashMap()
{
x.put(0, "www.stackoverflow.com");
}
}
In my test function, I am unable to create an object for some reason.
@Test
void test()
{
runTest();
}
public static void runTest()
{
PublisherHashMap y = new PublisherHashMap();
}
EDIT: I didn't construct the HashMap.
You are attempting to use x, the private HashMap, before it has been constructed. Hence you need to construct it first. You may do this by any of the following:
1) In the constructor:
x = new HashMap<Integer, String>();
// or diamond type
x = new HashMap<>();
2) In the class as a field of this class:
private static HashMap<Integer, String> x = new HashMap<>();
3) In the initializer block:
static {
x = new HashMap<>();
}
// or the no-static block
{
x = = new HashMap<>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With