简体   繁体   中英

How to call a hashmap & its values from other class in java?

我想创建5-6个类,我在第一个类中将值存储在hashmap中,我想从第4,第5和第6类调用它。如何获得这个任何片段或示例来实现这将是有帮助的,谢谢

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

}

you should use setters and getters for the hashmap.

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

Two reasonable approaches.

  1. Have a public getter for the Map. Class5 would the call class1.getMap().doSomething(). Not much work (good) and outside classes can do anything they want to the map, eg clear(), which may or may not be good.

  2. Write individual methods for the map, eg putIntoMap(), removeFromMap(), etc. More work but you can restrict what outsiders can do. If you don't want them able to clear(), don't write a ckearMap() method.

Purists have a "Law of Demeter" that says always do option 2 but IMHO that is often overkill.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM