Domanda

 public class CityList{
   public static void main(String[] args){
   ConcurrentHashMap<Integer,String> hm=new ConcurrentHashMap<Integer,String>();
   hm.put(10,"AAAA");
        hm.put(11."BBBB");
        }
        }
        // another class
        public class Getcity extends CityList{
        public static void main(String[] args){
        public void showcity(int i)
        {
        system.out.println(hm.get(i);
        }

I have created one class and implemented ConcurrentHashMap in that class.Now I want to access specific elements of that Map using another method which is in some other class. Please help me.If I pass i value as 10,it should display AAAA. Please tell me how to do this.

È stato utile?

Soluzione 2

You are a long way from where you think you are.

You are declaring and using the Map in he main() method. Local variables are inaccessible to "other classes", although they may be passed to methods/constructors of other classes (and final local variable are accessible to anonymous classes).

What does all that mean to you?

  • make the map a private field of a CityList
  • provide a getter for the map
  • have code in another class create an instance of CityList and access the map via its getter to populate it
  • have still other code test it from a main somewhere

Altri suggerimenti

You should create your other classes with a ConcurrentHashMapmember, and have the ConcurrentHashMap you created in your CityList class injected to those classes - either as a constructor argument or call a setter method.

Another option is to have a getter method in your CityList class, and have other classes access that getter.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top