Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a HashMap from a different class

Tags:

java

hashmap

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?

like image 338
Mr.Smithyyy Avatar asked Mar 22 '15 18:03

Mr.Smithyyy


People also ask

How do you pass a HashMap from one class to another?

Given a HashMap, there are three ways one can copy the given HashMap to another: By normally iterating and putting it to another HashMap using put(k, v) method. Using putAll() method. Using copy constructor.

How do you access a HashMap from another method?

This is simple and can be achieved by declaring the hashmap as public and making it a class variable. Now, since its public and. a class variable, it can be used in any function of the class, or outside with the help of that class's reference.

How do you call a HashMap from another method in Java?

Java HashMap Example The put() method inserts the elements in the map. To get the key and value elements, we should call the getKey() and getValue() methods. The Map.Entry interface contains the getKey() and getValue() methods. But, we should call the entrySet() method of Map interface to get the instance of Map.Entry.

Can we use any class as Map key?

Yes, we can use any object as key in a Map in java but we need to override the equals() and hashCode() methods of that object class.


1 Answers

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...
      }  
}
like image 88
vojta Avatar answered Sep 29 '22 18:09

vojta