Accessing a HashMap from a different class

前端 未结 6 1556
暗喜
暗喜 2020-12-30 08:02

I have a hashmap in my class titled DataStorage:

HashMap people = new HashMap();

people.put(\"bob\", 2);
peopl         


        
6条回答
  •  北海茫月
    2020-12-30 08:36

    If you need to share the same instance of a HashMap across your application, you need to create a singleton. Using a singleton guarantees that the same instance of the HashMap will always be referenced by anything trying to access it. For example for a HashMap:

    Singleton class:

    public class MyData {
    
        private static final MyData instance = new MyData ();
    
        private MyData () {     
                HashMap myDataMap = new HashMap();          
                   ... logic to populate the map
    
                this.referenceData = myDataMap;
    
        }
    
        public HashMap referenceData;
    
        public static DeviceData getInstance(){
            return instance;
        }
    }
    

    Usage in another class:

    HashMap referenceData = MyData.getInstance().referenceData;
    

提交回复
热议问题