Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my constructor work? (Java)

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.

like image 424
ML. Avatar asked Aug 10 '26 11:08

ML.


1 Answers

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<>();
}
like image 57
Andrew Tobilko Avatar answered Aug 13 '26 00:08

Andrew Tobilko