Accessing a HashMap from a different class

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

    You can either make your HashMap public, or create a getter for it:

    public HashMap getPeople() {
        return people;
    }
    

    then you can access it using an instance of the DataStorage class, like this:

    DataStorage dataStorage = new DataStorage();
    dataStorage.getPeople()
    

    or, if you also make both the getter and the HashMap static:

    DataStorage.getPeople()
    

    EDIT: Note, that if your instance variables are not specifically given access modifiers, they default to package access, which means that they can be accessed from other classes defined in the same package. More details about access modifiers can be found in the documentation, here's a brief summary:

    Access Levels

    Modifier    Class   Package Subclass    World
    public          Y         Y        Y        Y
    protected       Y         Y        Y        N
    no modifier     Y         Y        N        N
    private         Y         N        N        N
    

提交回复
热议问题