Mr.Smithyyy Mr.Smithyyy - 1 month ago 8
Java Question

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?

Answer

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...
      }  
}
Comments