我想创建某个类的多个实例,想公用一个HashMap对象,确保每个实例的HashMap一样,我想能用static,但不知道怎么用,自己试了没成功,请各位大师赐教

解决方案 »

  1.   

    public class Test{
       public static HashMap hm=new HashMap();
       .....
    }
    这样不行吗?
      

  2.   

    不知道你是怎么出错的,你的那种方法可行。package test.pancras;import java.util.HashMap;
    import java.util.Map;public class A {

    public static Map map = new HashMap();

    public String id;

    public A(String id) {
    super();
    this.id = id;
    }

    public String getId() {
    return id;
    } public void setId(String id) {
    this.id = id;
    }
    }
    测试代码

            public static void main(String[] args) {
    A a1 = new A("1");
    a1.map.put("1", "1");
    A a2 = new A("2");
    System.out.println(a2.map.get("1"));
    }
      

  3.   

    import java.util.HashMap;
    public class HashMapTest {
            
        /**
         * Creates a new instance of <code>HashMapTest</code>.
         */
        public HashMapTest() {
        
        }
        
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            MyClass my=new MyClass();
         my.put(1,1);
         MyClass you=new MyClass();
         you.put(2,2);
         System.out.println ("*"+my.hm.size()+"*");
         System.out.println ("*"+you.hm.size()+"*");
        }
    }
    class MyClass {
    public static HashMap hm=new HashMap();

    public void put(Object a,Object b){
    hm.put(a,b);
    }
    }