Accessing a HashMap from a different class












10















I have a hashmap in my class titled DataStorage:



HashMap<String, Integer> people = new HashMap<String, Integer>();

people.put("bob", 2);
people.put("susan", 5);


How can I access the data in this HashMap in a different class?










share|improve this question


















  • 2





    define it as static global variable and then you will be able to access it from different classes. public static HashMap<String, Integer> people = new HashMap<String, Integer>();

    – user4232819
    Mar 22 '15 at 18:06
















10















I have a hashmap in my class titled DataStorage:



HashMap<String, Integer> people = new HashMap<String, Integer>();

people.put("bob", 2);
people.put("susan", 5);


How can I access the data in this HashMap in a different class?










share|improve this question


















  • 2





    define it as static global variable and then you will be able to access it from different classes. public static HashMap<String, Integer> people = new HashMap<String, Integer>();

    – user4232819
    Mar 22 '15 at 18:06














10












10








10


4






I have a hashmap in my class titled DataStorage:



HashMap<String, Integer> people = new HashMap<String, Integer>();

people.put("bob", 2);
people.put("susan", 5);


How can I access the data in this HashMap in a different class?










share|improve this question














I have a hashmap in my class titled DataStorage:



HashMap<String, Integer> people = new HashMap<String, Integer>();

people.put("bob", 2);
people.put("susan", 5);


How can I access the data in this HashMap in a different class?







java hashmap






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 22 '15 at 18:02









Mr.SmithyyyMr.Smithyyy

1,19762459




1,19762459








  • 2





    define it as static global variable and then you will be able to access it from different classes. public static HashMap<String, Integer> people = new HashMap<String, Integer>();

    – user4232819
    Mar 22 '15 at 18:06














  • 2





    define it as static global variable and then you will be able to access it from different classes. public static HashMap<String, Integer> people = new HashMap<String, Integer>();

    – user4232819
    Mar 22 '15 at 18:06








2




2





define it as static global variable and then you will be able to access it from different classes. public static HashMap<String, Integer> people = new HashMap<String, Integer>();

– user4232819
Mar 22 '15 at 18:06





define it as static global variable and then you will be able to access it from different classes. public static HashMap<String, Integer> people = new HashMap<String, Integer>();

– user4232819
Mar 22 '15 at 18:06












6 Answers
6






active

oldest

votes


















8














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



public class DataStorage {
private HashMap<String, Integer> people = new HashMap<String, Integer>();

public HashMap<String, Integer> getPeopleMap() {
return people;
}
}

public class AnotherClass {
DataStorage x = new DataStorage();

private void someMethod() {
HashMap<String, Integer> people = x.getPeopleMap();
//work with your map here...
}
}





share|improve this answer































    3














    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<String, Integer> people = new HashMap<String, Integer>();

    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. :)






    share|improve this answer





















    • 1





      Too many lines of code for too little effect... This super-interface coding leads to unreadable, write-only code.

      – vojta
      Mar 23 '15 at 10:07






    • 2





      @vojta being able to treat the datastore as a plugin is not a little effect.

      – candied_orange
      Mar 23 '15 at 12:44



















    1














    You can access it:



    DataStorage storage = new DataStorage();
    HashMap<String, Integer> people = storage.people;





    share|improve this answer
























    • And public. : )

      – candied_orange
      Mar 22 '15 at 18:09











    • Or same package;)

      – Aleksander Mielczarek
      Mar 22 '15 at 18:09



















    1














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



    public HashMap<String, Integer> 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





    share|improve this answer

































      0














      This is eazy



      public class ListDataStorage {

      public static LinkedHashMap getHmapCashType(){

      LinkedHashMap<String, String> hMapCashType = new LinkedHashMap<String, String>();
      hMapCashType.put("A", "Cash");
      hMapCashType.put("B", "Credit");

      return hMapCashType;
      }
      }


      access hashmap data from another class



      String value = ListDataStorage.getHmapCashType().get("A").toString()





      share|improve this answer































        0














        If you need to share the same instance of a HashMap across your application, you need to create a singleton. Using a singleton guarantees that the same instance of the HashMap will always be referenced by anything trying to access it. For example for a HashMap<String,String>:



        Singleton class:



        public class MyData {

        private static final MyData instance = new MyData ();

        private MyData () {
        HashMap myDataMap = new HashMap<String, String>();
        ... logic to populate the map

        this.referenceData = myDataMap;

        }

        public HashMap<Integer, DeviceReference> referenceData;

        public static DeviceData getInstance(){
        return instance;
        }
        }


        Usage in another class:



        HashMap<String, String> referenceData = MyData.getInstance().referenceData;





        share|improve this answer


























        • This article states not to use singleton: alainschlesser.com/singletons-shared-instances

          – Timur Ozkul
          Feb 10 at 18:33











        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f29197899%2faccessing-a-hashmap-from-a-different-class%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        8














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



        public class DataStorage {
        private HashMap<String, Integer> people = new HashMap<String, Integer>();

        public HashMap<String, Integer> getPeopleMap() {
        return people;
        }
        }

        public class AnotherClass {
        DataStorage x = new DataStorage();

        private void someMethod() {
        HashMap<String, Integer> people = x.getPeopleMap();
        //work with your map here...
        }
        }





        share|improve this answer




























          8














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



          public class DataStorage {
          private HashMap<String, Integer> people = new HashMap<String, Integer>();

          public HashMap<String, Integer> getPeopleMap() {
          return people;
          }
          }

          public class AnotherClass {
          DataStorage x = new DataStorage();

          private void someMethod() {
          HashMap<String, Integer> people = x.getPeopleMap();
          //work with your map here...
          }
          }





          share|improve this answer


























            8












            8








            8







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



            public class DataStorage {
            private HashMap<String, Integer> people = new HashMap<String, Integer>();

            public HashMap<String, Integer> getPeopleMap() {
            return people;
            }
            }

            public class AnotherClass {
            DataStorage x = new DataStorage();

            private void someMethod() {
            HashMap<String, Integer> people = x.getPeopleMap();
            //work with your map here...
            }
            }





            share|improve this answer













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



            public class DataStorage {
            private HashMap<String, Integer> people = new HashMap<String, Integer>();

            public HashMap<String, Integer> getPeopleMap() {
            return people;
            }
            }

            public class AnotherClass {
            DataStorage x = new DataStorage();

            private void someMethod() {
            HashMap<String, Integer> people = x.getPeopleMap();
            //work with your map here...
            }
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 22 '15 at 18:08









            vojtavojta

            4,28321647




            4,28321647

























                3














                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<String, Integer> people = new HashMap<String, Integer>();

                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. :)






                share|improve this answer





















                • 1





                  Too many lines of code for too little effect... This super-interface coding leads to unreadable, write-only code.

                  – vojta
                  Mar 23 '15 at 10:07






                • 2





                  @vojta being able to treat the datastore as a plugin is not a little effect.

                  – candied_orange
                  Mar 23 '15 at 12:44
















                3














                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<String, Integer> people = new HashMap<String, Integer>();

                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. :)






                share|improve this answer





















                • 1





                  Too many lines of code for too little effect... This super-interface coding leads to unreadable, write-only code.

                  – vojta
                  Mar 23 '15 at 10:07






                • 2





                  @vojta being able to treat the datastore as a plugin is not a little effect.

                  – candied_orange
                  Mar 23 '15 at 12:44














                3












                3








                3







                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<String, Integer> people = new HashMap<String, Integer>();

                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. :)






                share|improve this answer















                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<String, Integer> people = new HashMap<String, Integer>();

                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. :)







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 22 '15 at 22:02

























                answered Mar 22 '15 at 18:42









                candied_orangecandied_orange

                4,3421649




                4,3421649








                • 1





                  Too many lines of code for too little effect... This super-interface coding leads to unreadable, write-only code.

                  – vojta
                  Mar 23 '15 at 10:07






                • 2





                  @vojta being able to treat the datastore as a plugin is not a little effect.

                  – candied_orange
                  Mar 23 '15 at 12:44














                • 1





                  Too many lines of code for too little effect... This super-interface coding leads to unreadable, write-only code.

                  – vojta
                  Mar 23 '15 at 10:07






                • 2





                  @vojta being able to treat the datastore as a plugin is not a little effect.

                  – candied_orange
                  Mar 23 '15 at 12:44








                1




                1





                Too many lines of code for too little effect... This super-interface coding leads to unreadable, write-only code.

                – vojta
                Mar 23 '15 at 10:07





                Too many lines of code for too little effect... This super-interface coding leads to unreadable, write-only code.

                – vojta
                Mar 23 '15 at 10:07




                2




                2





                @vojta being able to treat the datastore as a plugin is not a little effect.

                – candied_orange
                Mar 23 '15 at 12:44





                @vojta being able to treat the datastore as a plugin is not a little effect.

                – candied_orange
                Mar 23 '15 at 12:44











                1














                You can access it:



                DataStorage storage = new DataStorage();
                HashMap<String, Integer> people = storage.people;





                share|improve this answer
























                • And public. : )

                  – candied_orange
                  Mar 22 '15 at 18:09











                • Or same package;)

                  – Aleksander Mielczarek
                  Mar 22 '15 at 18:09
















                1














                You can access it:



                DataStorage storage = new DataStorage();
                HashMap<String, Integer> people = storage.people;





                share|improve this answer
























                • And public. : )

                  – candied_orange
                  Mar 22 '15 at 18:09











                • Or same package;)

                  – Aleksander Mielczarek
                  Mar 22 '15 at 18:09














                1












                1








                1







                You can access it:



                DataStorage storage = new DataStorage();
                HashMap<String, Integer> people = storage.people;





                share|improve this answer













                You can access it:



                DataStorage storage = new DataStorage();
                HashMap<String, Integer> people = storage.people;






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 22 '15 at 18:06









                Aleksander MielczarekAleksander Mielczarek

                1,88011433




                1,88011433













                • And public. : )

                  – candied_orange
                  Mar 22 '15 at 18:09











                • Or same package;)

                  – Aleksander Mielczarek
                  Mar 22 '15 at 18:09



















                • And public. : )

                  – candied_orange
                  Mar 22 '15 at 18:09











                • Or same package;)

                  – Aleksander Mielczarek
                  Mar 22 '15 at 18:09

















                And public. : )

                – candied_orange
                Mar 22 '15 at 18:09





                And public. : )

                – candied_orange
                Mar 22 '15 at 18:09













                Or same package;)

                – Aleksander Mielczarek
                Mar 22 '15 at 18:09





                Or same package;)

                – Aleksander Mielczarek
                Mar 22 '15 at 18:09











                1














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



                public HashMap<String, Integer> 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





                share|improve this answer






























                  1














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



                  public HashMap<String, Integer> 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





                  share|improve this answer




























                    1












                    1








                    1







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



                    public HashMap<String, Integer> 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





                    share|improve this answer















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



                    public HashMap<String, Integer> 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






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 22 '15 at 18:26

























                    answered Mar 22 '15 at 18:12









                    AtomHeartFatherAtomHeartFather

                    6701132




                    6701132























                        0














                        This is eazy



                        public class ListDataStorage {

                        public static LinkedHashMap getHmapCashType(){

                        LinkedHashMap<String, String> hMapCashType = new LinkedHashMap<String, String>();
                        hMapCashType.put("A", "Cash");
                        hMapCashType.put("B", "Credit");

                        return hMapCashType;
                        }
                        }


                        access hashmap data from another class



                        String value = ListDataStorage.getHmapCashType().get("A").toString()





                        share|improve this answer




























                          0














                          This is eazy



                          public class ListDataStorage {

                          public static LinkedHashMap getHmapCashType(){

                          LinkedHashMap<String, String> hMapCashType = new LinkedHashMap<String, String>();
                          hMapCashType.put("A", "Cash");
                          hMapCashType.put("B", "Credit");

                          return hMapCashType;
                          }
                          }


                          access hashmap data from another class



                          String value = ListDataStorage.getHmapCashType().get("A").toString()





                          share|improve this answer


























                            0












                            0








                            0







                            This is eazy



                            public class ListDataStorage {

                            public static LinkedHashMap getHmapCashType(){

                            LinkedHashMap<String, String> hMapCashType = new LinkedHashMap<String, String>();
                            hMapCashType.put("A", "Cash");
                            hMapCashType.put("B", "Credit");

                            return hMapCashType;
                            }
                            }


                            access hashmap data from another class



                            String value = ListDataStorage.getHmapCashType().get("A").toString()





                            share|improve this answer













                            This is eazy



                            public class ListDataStorage {

                            public static LinkedHashMap getHmapCashType(){

                            LinkedHashMap<String, String> hMapCashType = new LinkedHashMap<String, String>();
                            hMapCashType.put("A", "Cash");
                            hMapCashType.put("B", "Credit");

                            return hMapCashType;
                            }
                            }


                            access hashmap data from another class



                            String value = ListDataStorage.getHmapCashType().get("A").toString()






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Oct 28 '16 at 6:10









                            Tharindu BandaraTharindu Bandara

                            46067




                            46067























                                0














                                If you need to share the same instance of a HashMap across your application, you need to create a singleton. Using a singleton guarantees that the same instance of the HashMap will always be referenced by anything trying to access it. For example for a HashMap<String,String>:



                                Singleton class:



                                public class MyData {

                                private static final MyData instance = new MyData ();

                                private MyData () {
                                HashMap myDataMap = new HashMap<String, String>();
                                ... logic to populate the map

                                this.referenceData = myDataMap;

                                }

                                public HashMap<Integer, DeviceReference> referenceData;

                                public static DeviceData getInstance(){
                                return instance;
                                }
                                }


                                Usage in another class:



                                HashMap<String, String> referenceData = MyData.getInstance().referenceData;





                                share|improve this answer


























                                • This article states not to use singleton: alainschlesser.com/singletons-shared-instances

                                  – Timur Ozkul
                                  Feb 10 at 18:33
















                                0














                                If you need to share the same instance of a HashMap across your application, you need to create a singleton. Using a singleton guarantees that the same instance of the HashMap will always be referenced by anything trying to access it. For example for a HashMap<String,String>:



                                Singleton class:



                                public class MyData {

                                private static final MyData instance = new MyData ();

                                private MyData () {
                                HashMap myDataMap = new HashMap<String, String>();
                                ... logic to populate the map

                                this.referenceData = myDataMap;

                                }

                                public HashMap<Integer, DeviceReference> referenceData;

                                public static DeviceData getInstance(){
                                return instance;
                                }
                                }


                                Usage in another class:



                                HashMap<String, String> referenceData = MyData.getInstance().referenceData;





                                share|improve this answer


























                                • This article states not to use singleton: alainschlesser.com/singletons-shared-instances

                                  – Timur Ozkul
                                  Feb 10 at 18:33














                                0












                                0








                                0







                                If you need to share the same instance of a HashMap across your application, you need to create a singleton. Using a singleton guarantees that the same instance of the HashMap will always be referenced by anything trying to access it. For example for a HashMap<String,String>:



                                Singleton class:



                                public class MyData {

                                private static final MyData instance = new MyData ();

                                private MyData () {
                                HashMap myDataMap = new HashMap<String, String>();
                                ... logic to populate the map

                                this.referenceData = myDataMap;

                                }

                                public HashMap<Integer, DeviceReference> referenceData;

                                public static DeviceData getInstance(){
                                return instance;
                                }
                                }


                                Usage in another class:



                                HashMap<String, String> referenceData = MyData.getInstance().referenceData;





                                share|improve this answer















                                If you need to share the same instance of a HashMap across your application, you need to create a singleton. Using a singleton guarantees that the same instance of the HashMap will always be referenced by anything trying to access it. For example for a HashMap<String,String>:



                                Singleton class:



                                public class MyData {

                                private static final MyData instance = new MyData ();

                                private MyData () {
                                HashMap myDataMap = new HashMap<String, String>();
                                ... logic to populate the map

                                this.referenceData = myDataMap;

                                }

                                public HashMap<Integer, DeviceReference> referenceData;

                                public static DeviceData getInstance(){
                                return instance;
                                }
                                }


                                Usage in another class:



                                HashMap<String, String> referenceData = MyData.getInstance().referenceData;






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Nov 15 '18 at 23:25

























                                answered Nov 15 '18 at 22:44









                                Chris HalcrowChris Halcrow

                                11.1k46991




                                11.1k46991













                                • This article states not to use singleton: alainschlesser.com/singletons-shared-instances

                                  – Timur Ozkul
                                  Feb 10 at 18:33



















                                • This article states not to use singleton: alainschlesser.com/singletons-shared-instances

                                  – Timur Ozkul
                                  Feb 10 at 18:33

















                                This article states not to use singleton: alainschlesser.com/singletons-shared-instances

                                – Timur Ozkul
                                Feb 10 at 18:33





                                This article states not to use singleton: alainschlesser.com/singletons-shared-instances

                                – Timur Ozkul
                                Feb 10 at 18:33


















                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f29197899%2faccessing-a-hashmap-from-a-different-class%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Florida Star v. B. J. F.

                                Danny Elfman

                                Lugert, Oklahoma