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.

4
  • You didn't declare the type of instance. Commented Jul 13, 2013 at 1:24
  • 5
    You need to synchronize the getInstance() method. Commented Jul 13, 2013 at 1:26
  • Very good point. It will guarantee only one instance. Commented Jul 13, 2013 at 1:37
  • 1
    It will also solve the problem, by enforcing the necessary memory-model constraints. Commented Jul 13, 2013 at 1:46

1 Answer 1

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
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

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?
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)
Thanks for explain. There could be more but this is the most important idea to know.
Here's something you can look at; it gives some great info on Enums: Java Enums

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.