0

Following the answers of this question: How can I initialise a static Map? I'm trying to create a static Map in my project.
Below a code snippet:

public class MyClass {

    public static final Map<String, String> dataMap;

    static {
        Map<String, String> tempMap = new HashMap<String, String>();
        try {
           // Getting a string value from a file, e.g. String data
           String data = "data";
           tempMap.put("firstData", data);
        }
        catch(Exception e) {}

        dataMap = Collections.unmodifiableMap(tempMap);

        //DEBUG (I test it and it correctly prints "data")
        System.out.println(dataMap.get("firstData"));
     }
}

Then I call the map in another class, like this:

public class AnotherClass {

   @Before
   public void MyMethod() {
      System.out.println(MyClass.dataMap.get("firstData"));
   }

   @Test
   public void testMethod() {}
}

Now it prints null, instead of the value "data".
Why?

Community
  • 1
  • 1
PenguinEngineer
  • 295
  • 1
  • 8
  • 30

2 Answers2

0

Are you sure your map is not modified somewhere else (cleared, ...) ? Because this code should work.

I don't think that "unmodifiableMap" is usefull when you are using "final", it just protects that the map will not be modified by reference. So values can change by an external call.

cactuschibre
  • 1,908
  • 2
  • 18
  • 36
  • The only difference seems to be that the method MyMethod is annotated with @Before annotation, because it is a test – PenguinEngineer Apr 01 '17 at 15:38
  • 3
    unmodifiableMap() is very important. Otherwise, you can just get a reference to that map and clear it (or adding/removing elements) from anywhere, although that is probably not desired. – JB Nizet Apr 01 '17 at 15:39
  • @PenguinEngineer post a complete minimal example reproducing the problem. – JB Nizet Apr 01 '17 at 15:40
0

When I executing the same code on my machine it's work and print data twice as you excpected , This code is not your problem.

UPDATE: maybe MyClass refer to another MyClass in your package? check your imports.. try to compile in and run it from the command line and check if you get the same results , there is something you missing here

Ron Badur
  • 1,873
  • 2
  • 15
  • 34