0

I have this code defined.

public class AAA {
    public static final Map<String, String> gList = new HashMap<> {{
        put("xxx", "xxx");
        put ....
    }};
    public static AAA instance;
    public static AAA getInstance() {
        if (instance == null)
            instance = new AAA();
        return instance;
    }

    public String calledFunc(String k) {
        return gList.get(k);    
    }
}

public class BBB {
    ...
    public void callingFunc(String k) {
        AAA.getInstance().calledFunc(k);  // <=  NULL pointer some time
    }
}

Is this because memory allocation failure or it will be freed some where. Just don't understand what wrong in my code. Maybe this is not reliable way to initialize.

Brigham
  • 14,395
  • 3
  • 38
  • 48
Yan Gao
  • 181
  • 1
  • 3
  • 11

1 Answers1

1

I tried doing something similar to this a while back for holding data between classes, I eventually went with an Enum

Try something like this perhaps?

public enum AAA {
    INSTANCE;
    public static final Map<String, String> gList = new HashMap<> {{
        put("xxx", "xxx");
        put ....
    }};
    public String calledFunc(String k) {
        return gList.get(k);
    }
}

If you did this, you wouldn't really need the function in the Enum since you could just do

public class BBB {
    ...
    public void callingFunc(String k) {
        AAA.gList.get(k);  // <=  NULL pointer some time
    }
}
Kyle Colantonio
  • 454
  • 1
  • 3
  • 21
  • This my pretty confused part in java to use enum. So what could be difference between enum and class? Is the way to do initialize? – Yan Gao Jul 13 '13 at 01:48
  • When using an Enum, you only allow one instance to be created, and that's typically done when you start the program. The difference between a class and an Enum is that a class can be instantiated multiple times (xxx = new AAA();) unless you specifically make it so you can only create one instance. In simple terms, Enums are kind of just a cleaner and easier way to make a single instance of a class that can be used to share data, information and even methods across other classes. (That's from my understanding, but I could be wrong at some parts) – Kyle Colantonio Jul 13 '13 at 01:57
  • Thanks for explain. There could be more but this is the most important idea to know. – Yan Gao Jul 13 '13 at 02:18
  • Here's something you can look at; it gives some great info on Enums: **[Java Enums](http://stackoverflow.com/questions/4709175/why-and-what-for-java-enum)** – Kyle Colantonio Jul 13 '13 at 02:38