-1

There is a static Map in a class initialized as Map but their is no implementation of Map interface like HashMap or TreeMap in this class. Now I need to create a unit test case where I need to use this map in my project. but when I am trying to create an implementation of this in other class , I found null object every time. I think I am missing some core concept of java programming . Please help me in resolving this issue.

Here is class spinet using static map:

public static Map<Integer, someSpace> someSpaceMap = null;
public static boolean loadMyCache(){

    try {
        someSpaceMap = cacheService.getsomeSpaces();

    } catch (Throwable e) {
        e.printStackTrace();
        return false;
    }
}

3 Answers3

1

try this

public static Map<Integer, someSpace> someSpaceMap = null;
static {
    try {
        someSpaceMap = CacheService.getsomeSpaces();
    } catch (Throwable e) { // Discouraged
        e.printStackTrace();
    }
}
Adam Yost
  • 3,616
  • 23
  • 36
0

Thanks everyone ,I found solution for this .I can initialize this outside of class using any map implementation. Just keep in mind if you are using java version lower than 5 , make sure primitives should be changed into Wrapper class object because Map interface signature is like this: public interface Map < K, V >.Java 1.4 do not support auto-boxing.

0

Couple of things firstly, fix your naming conventions to align with the Java standard.

public static Map<Integer, someSpace> someSpaceMap = null;

someSpace should be SomeSpace as it's a class name.

As the cache service is not defined, I'm assuming its a static call, you'll need to fix the case on the method name too

someSpaceMap = CacheService.getSomeSpaces();

Next, you can initialise a Map with values when you declare it, like so:

import java.util.HashMap;
import java.util.Map;

public class TestRunner {

    public static Map<Integer, SomeSpace> someSpaceMap = new HashMap<Integer, SomeSpace>(){{
        put(1, new SomeSpace());
        put(2, new SomeSpace());
        put(3, new SomeSpace());
    }};

    public static void main(String[] args) {
        for(Map.Entry e : someSpaceMap.entrySet()){
            System.out.println("key " + e.getKey() + " value " + e.getValue());
        }
    }
}

class SomeSpace {}

Sample output

key 1 value com.SomeSpace@4e50df2e
key 2 value com.SomeSpace@1d81eb93
key 3 value com.SomeSpace@7291c18f
Jimmy
  • 16,123
  • 39
  • 133
  • 213
  • Please don't recommend using instance initialization blocks. See http://stackoverflow.com/q/671644/95725 – NamshubWriter Mar 05 '15 at 04:40
  • @NamshubWriter thanks for pointing that out, TIL equality is an issue when instantiating collections that way ;) On another note, it seems there are many ways of doing this : http://stackoverflow.com/questions/507602/how-can-i-initialize-a-static-map – Jimmy Mar 05 '15 at 04:53