Accessing a HashMap from a different class

前端 未结 6 1570
暗喜
暗喜 2020-12-30 08:02

I have a hashmap in my class titled DataStorage:

HashMap people = new HashMap();

people.put(\"bob\", 2);
peopl         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-30 08:27

    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 people = new HashMap();
    
            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. :)

提交回复
热议问题