我想在我的HashMap中放入我的String,Double...还有Object 能不能做到自到装包\拆包,
谢谢了,如果可以,给个例子。谢谢了!

解决方案 »

  1.   

    是,就想让一个hashmap中放入不同的类型。有没有好的建议呀
      

  2.   

    这就不行了
    HashMap<K,V>
      

  3.   

    具体一点,我看文档里面new的时候就就指定类型了。能不能具体一点。谢谢了!
      

  4.   

    你试一下下面的例子:
      class Sim<T>{
             private T ob;
             public  Sim(T s){ob=s;}
             public T getob(){return ob;}
             public void showType(){
                    System.out.println("Type of T is " + ob.getClass().getName());
                  }
             }class GenDemo{
       public static void main(String[] args){
             Sim<Integer>iOb;
             iOb=new Sim<Integer>(88);
             iOb.showType();
             int v=iOb.getob();
             System.out.println("value: "+v);
     
             Sim<String>StrOb;
             StrOb=new Sim<String>("Generics Test");
             StrOb.showType();
             String str=StrOb.getob();
             System.out.println("value: "+str);
           }
        
        }
             
             
      

  5.   

    需要说明的是上面的例子是出自<<Java:The Complete Reference,J2SE 5 Edition>>,只是做了一些小小的改动。
    如果你想看原例子的话就找它的中文版看看《Java J2SE 5 Edition 参考大全》清华大学出版社
      

  6.   

    哈哈,解决了,若是有更好的办法,请指教了
    感谢  yanruilin()   的例子!
    import java.util.*;
    /**
     *
     * @author Administrator
     */
    public class TestHashMap<Key, Value>{
        public HashMap<Key, Value> h=new HashMap<Key, Value>();
        public void put(Key k, Value v) {
            h.put(k,v);
        }
        
        public Value get(Key k) {
            return h.get(k);
        }
        
        public static void main(String args[]){
    //        Sim<Integer>iOb;
    //        iOb=new Sim<Integer>(88);
            Sim<String>iOb;
            iOb=new Sim<String>("xxx...");
            TestHashMap<String,Sim> t=new TestHashMap<String,Sim>();
            t.put("key", iOb);
            Sim b;
            b = t.get("key");
            b.showType();
        }
        
    }
    class Sim <T>{
        
        private T ob;
        public  Sim(T s){
            ob=s;
        }
        public T getob(){
            return ob;
        }
        public void showType(){
            System.out.println("Type of T is " + ob.getClass().getName());
        }
    }