Accessing a HashMap from a different class

前端 未结 6 1572
暗喜
暗喜 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:22

    Create your HashMap as an instance variable and provide a method to access it into your class API:

    public class DataStorage {
        private HashMap people = new HashMap();
    
        public HashMap getPeopleMap() {
             return people;
        }
    }
    
    public class AnotherClass {
          DataStorage x = new DataStorage();       
    
          private void someMethod() {
               HashMap people = x.getPeopleMap();
               //work with your map here...
          }  
    }
    

提交回复
热议问题