如何从其他类Method访问ConcurrentHashMap元素

时间:2013-09-17 05:35:49

标签: java concurrenthashmap

 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);
        }

我创建了一个类并在该类中实现了ConcurrentHashMap。现在我想使用另一个类中的另一个方法访问该Map的特定元素。请帮助我。如果我将 i 值传递为10,则应显示AAAA。请告诉我怎么做。

2 个答案:

答案 0 :(得分:4)

您应该使用ConcurrentHashMap成员创建其他类,并将您在ConcurrentHashMap类中创建的CityList注入到这些类中 - 作为构造函数参数或调用setter方法

另一个选择是在CityList类中使用getter方法,并让其他类访问该getter。

答案 1 :(得分:2)

你离你的想象很远。

您正在main()方法中声明并使用Map。局部变量对于“其他类”是不可访问的,尽管它们可以传递给其他类的方法/构造函数(并且匿名类可以访问最终的局部变量)。

这对你意味着什么?

  • 将地图设为CityList的私有字段
  • 为地图提供吸气剂
  • 让另一个类中的代码创建CityList的实例并通过其getter访问地图以填充它
  • 还有其他代码在某个地方测试它
相关问题