11

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?

Mr.Smithyyy
  • 2,157
  • 12
  • 49
  • 95
  • 2
    define it as static global variable and then you will be able to access it from different classes. `public static HashMap people = new HashMap();` –  Mar 22 '15 at 18:06

6 Answers6

14

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...
      }  
}
vojta
  • 5,591
  • 2
  • 24
  • 64
  • is there a way to set the hashmap also from AnotherClass without making people public in DataStorage? – Anu Aug 28 '20 at 13:11
3

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 AnotherClasss 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. :)

Community
  • 1
  • 1
candied_orange
  • 7,036
  • 2
  • 28
  • 62
2

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
AtomHeartFather
  • 954
  • 17
  • 35
1

You can access it:

DataStorage storage = new DataStorage();
HashMap<String, Integer> people = storage.people;
Aleksander Mielczarek
  • 2,787
  • 1
  • 24
  • 43
1

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;
Chris Halcrow
  • 28,994
  • 18
  • 176
  • 206
0

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()