How to call hashmap & its values โ€‹โ€‹from another class in java?

I would like to create 5-6 classes, I store the values โ€‹โ€‹in the hashmap in the 1st class, and I would like to name it from the 4th, 5th and 6th classes. How to get this, any snippets or examples to implement this will be helpful, thanks

+4
source share
3 answers
public class Example { private HashMap<String, String> hashmap = new HashMap<String, String>(); public HashMap<String, String> getHashmap() { return hashmap; } public void setHashmap(HashMap<String, String> hashmap) { this.hashmap = hashmap; } } public class AnotherClass { public static void main(String args[]) { Example ex = new Example(); HashMap<String, String> hm = ex.getHashmap(); } } 
+10
source

you must use setters and getters for the hash map.

 private HashMap h = null; //instantiate hashmap in the constructor public ... //add value to hashmap public void add(Object value) { h.put(value);//eventually cast value or declare it as you did it in the hashmap } //get hashmap public HashMap getMap() { return h; } //set hashmap public void setMap(HashMap hm) { h=hm; }... 
0
source

Two reasonable approaches.

  • Perform a public receiver for the Card. Class5 will call class1.getMap (). DoSomething (). Not many (good) and external classes can do whatever they want on the map, for example. clear (), which may or may not be good.

  • Write separate methods for the map, for example. putIntoMap (), removeFromMap (), etc. More work, but you can limit what outsiders can do. If you do not want them to be able to clear (), do not write the ckearMap () method.

Purists have the "Law of Demeter", which says that there is always option 2, but IMHO, which is often unnecessary.

0
source

Source: https://habr.com/ru/post/1389208/


All Articles