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?
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.
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.
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.
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.
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...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With