首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2EE开发 >

求好手帮忙啊关于泛型和重载

2012-06-24 
求高手帮忙啊,关于泛型和重载Java codepublic class Bean2Map {public static HashMap format(TbAccount i

求高手帮忙啊,关于泛型和重载

Java code
public class Bean2Map {    public static HashMap format(TbAccount in){        HashMap map=new HashMap();        map.put(MyKey.TBACCOUNT.NAME, in.getName());        map.put(MyKey.TBACCOUNT.ACCOUNT, in.getAccount());        map.put(MyKey.TBACCOUNT.PASSWORD, in.getPassword());        map.put(MyKey.TBACCOUNT.SEX, in.getSex());        return map;    }        public static HashMap format(TbDish in){        HashMap map=new HashMap();        map.put(MyKey.TBDISH.NAME, in.getName());        map.put(MyKey.TBDISH.KIND, in.getKind().getName());        map.put(MyKey.TBDISH.PRICE, in.getPrice()+"");        map.put(MyKey.TBDISH.ID, in.getDishId().toString());        return map;    }         public static HashMap format(TbRestaurant in){        HashMap map=new HashMap();        map.put(MyKey.TBRESTAURANT.ID, in.getRestaurantId().toString());            return map;    }           public static HashMap format(Object in){        HashMap map=new HashMap();       map.put("ob", "ob");            return map;    }        public static List<HashMap> formatDishList(List<TbDish> in){        List<HashMap> list=new ArrayList<HashMap>();        for (TbDish dish : in) {            list.add(format(dish));        }        return list;    }         public static <T> List<HashMap> format(List<T> in){        List<HashMap> list=new ArrayList<HashMap>();        for (T item : in) {                        list.add(format(item));        }        return list;    }    }


当我用format(list),(list是List<TbRestaurant>类型)为什么for循环里面调用的是format(Object in)而不是format(TbRestaurant in)啊 求指教啊!!

[解决办法]
这是泛型擦除
也就是说编译的时候T被擦除,取而代之的是Object(即在.class文件中没有T的信息,只有Object信息)
所以
for (T item : in) 被编译为 for (Objec item : in) --.class文件的伪代码被编译为这样的信息
而编译期不知道用户会传入什么样的T,所以不可能编译为 for (TbRestaurant item : in)
所以item就是Object类型而不是TbRestauant类型,所以就会调用参数为Object的format方法

热点排行
Bad Request.