Concept of creating static Map
I want to create a Map object that can lose value only if we explicitly delete it from map. I have created Map object like
开发者_运维百科public static Map<Long,String> listUser =new HasMap<Long,String>();
but every time class object is created new instance of Map is also created that contain null value. I want to create a Map instance that contain value we stored before.
static
here means that the object is created once for the whole life of the executing program (or server)
If you want to store it between program executions, you need serialization.
Your problem is that you're creating new versions of a variable that already exists. Just use the one that's created by the compiler. Here's a quick example:
class Example{
public static Map<Long,String> listUser =new HashMap<Long,String>();
}
// other file
class Main{
public static int main(String args[]){
// Notice how I didn't have to do Example.listUser = new HashMap<etc> here
Example.listUser.add(12, "Bob");
Example.listUser.add(50, "George");
}
}
You are describing the default behavior of Maps, they remember entries. The problem I think you are having is that you probably need only one Map and not new instances. If you need a second map that has the contents of the first, look into "copy constructors" but your question as stated doesn't suggest that would be a good idea.
精彩评论