简体   繁体   中英

Accessing a HashMap from a different class

I have a hashmap in my class titled DataStorage:

HashMap<String, Integer> people = new HashMap<String, Integer>();

people.put("bob", 2);
people.put("susan", 5);

How can I access the data in this HashMap in a different class?

Create your HashMap as an instance variable and provide a method to access it into your class API:

public class DataStorage {
    private HashMap<String, Integer> people = new HashMap<String, Integer>();

    public HashMap<String, Integer> getPeopleMap() {
         return people;
    }
}

public class AnotherClass {
      DataStorage x = new DataStorage();       

      private void someMethod() {
           HashMap<String, Integer> people = x.getPeopleMap();
           //work with your map here...
      }  
}

As an advocate of tell don't ask I'd like to show how this can be done without any getters.

public class TellDontAsk {

    interface MapSetter {
        public void setMap(Map map);
    }

    interface MapGiver {
        public void giveMap(MapSetter acceptMap);
    }

    public static void main(String[] args) {
        HashMap<String, Integer> people = new HashMap<String, Integer>();

        people.put("bob", 2);
        people.put("susan", 5);

        DataStorage ds = new DataStorage();
        ds.setMap(people);

        AnotherClass ac = new AnotherClass();
        ds.giveMap(ac);

        ac.displayMap();
    }

    public static class DataStorage implements MapSetter, MapGiver {
        private Map map;

        @Override
        public void setMap(Map map) {
            this.map = map;            
        }

        @Override
        public void giveMap(MapSetter acceptMap) {
            acceptMap.setMap(map);

        }
    }

    public static class AnotherClass implements MapSetter {
        private Map map;

        public void displayMap() {
            System.out.println(map);

        }

        @Override
        public void setMap(Map map) {
            this.map = map;            
        }  
    }
}

Outputs:

{bob=2, susan=5}

Notice how DataStorage has no knowlege of AnotherClass s existence? Nor does AnotherClass know about DataStorage . All they share is an interface. This means you're free to do whatever you like in either class so long as you keep supporting that interface.

BTW, the classes are only static because I was to lazy to move them into their own files. :)

You can access it:

DataStorage storage = new DataStorage();
HashMap<String, Integer> people = storage.people;

You can either make your HashMap public, or create a getter for it:

public HashMap<String, Integer> getPeople() {
    return people;
}

then you can access it using an instance of the DataStorage class, like this:

DataStorage dataStorage = new DataStorage();
dataStorage.getPeople()

or, if you also make both the getter and the HashMap static:

DataStorage.getPeople()

EDIT: Note, that if your instance variables are not specifically given access modifiers, they default to package access, which means that they can be accessed from other classes defined in the same package. More details about access modifiers can be found in the documentation , here's a brief summary:

Access Levels

Modifier    Class   Package Subclass    World
public          Y         Y        Y        Y
protected       Y         Y        Y        N
no modifier     Y         Y        N        N
private         Y         N        N        N

This is eazy

public class ListDataStorage {

            public static LinkedHashMap getHmapCashType(){

                LinkedHashMap<String, String> hMapCashType = new LinkedHashMap<String, String>();
                hMapCashType.put("A", "Cash");
                hMapCashType.put("B", "Credit");

                return hMapCashType;
            }
    }

access hashmap data from another class

String value = ListDataStorage.getHmapCashType().get("A").toString()

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<String,String> :

Singleton class:

public class MyData {

    private static final MyData instance = new MyData ();

    private MyData () {     
            HashMap myDataMap = new HashMap<String, String>();          
               ... logic to populate the map

            this.referenceData = myDataMap;

    }

    public HashMap<Integer, DeviceReference> referenceData;

    public static DeviceData getInstance(){
        return instance;
    }
}

Usage in another class:

HashMap<String, String> referenceData = MyData.getInstance().referenceData;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM