java - HashMap created in Main method want to access in other functions -


i have hashmap in main , want access function ?

public class slr{      public static first(string fst){          *want access entire hashmap here      }      public static void main (string[] args){          hashmap<string, string> mymap = new hashmap<string, string>();          added data mymap      }   } 

there number of ways this. preferrably, might consider using class instance field, since don't have instance of class, won't work here (at least not far code has gone).

you use static field, leads bad habits better avoided (static not friend , bury in pile of problems , issues if not used carefully).

in case, 1 of better solutions change first method take map 1 of parameters, example...

public class slr{      public static first(string fst, map<string, string> mymap){          *want access entire hashmap here      }      public static void main (string[] args){          hashmap<string, string> mymap = new hashmap<string, string>();         first(somestring, mymap);      }   } 

this has benefit of allowing use different instances maps getting repeated/re-usable functionality first method

you might alos have read through code conventions java tm programming language, make easier people read code , read others

example of using class instance field

public class slr{      private map<string, string> mymap;      public slr() {         mymap = new hashmap<string, string>(25);     }      public slr(map<string, string> map) {         mymap = map     }      public first(string fst){         mymap.get(...); // or ever...         }      public static void main (string[] args){          slr slr = new slr();         slr.first(somestring);          hashmap<string, string> mymap = new hashmap<string, string>();         slr othersrl = new slr(mymap);         othersrl .first(somestring);      }   } 

there's not enough context question tell might want use, you'll need make choice yourself


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -