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<>();
}
You must change your declaration from
private static HashMap<Integer, String> x;
to
private static HashMap<Integer, String> x = new HashMap<Integer, String>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.