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

kagami318 2012-06-23 05:54:10
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)啊 求指教啊!!
...全文
62 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
qybao 2012-06-23
  • 打赏
  • 举报
回复
没有
只能在循环中自己判断
比如
for (T item : in) {
if (item intanceof xxx) {format((xxx)item);} //只能强行转换为相应的类型
else format(item);
}

kagami318 2012-06-23
  • 打赏
  • 举报
回复
谢谢3L!!!
那有没有其他方法让for循环里的format重载正确的对应类型的方法呢?
qybao 2012-06-23
  • 打赏
  • 举报
回复
这是泛型擦除
也就是说编译的时候T被擦除,取而代之的是Object(即在.class文件中没有T的信息,只有Object信息)
所以
for (T item : in) 被编译为 for (Objec item : in) --.class文件的伪代码被编译为这样的信息
而编译期不知道用户会传入什么样的T,所以不可能编译为 for (TbRestaurant item : in)
所以item就是Object类型而不是TbRestauant类型,所以就会调用参数为Object的format方法

kagami318 2012-06-23
  • 打赏
  • 举报
回复
单我用List<TbRestaurant>做参数是确实是调用了 public static <T> List<HashMap> format(List<T> in),不过 public static <T> List<HashMap> format(List<T> in)里for循环里的format却是调用了public static HashMap format(Object in) 因为这时T是TbRestaurant,难道不是应该调用 public static HashMap format(TbRestaurant in)吗????
脉动 2012-06-23
  • 打赏
  • 举报
回复
List<TbRestaurant>,肯定匹配的是Object,怎么会匹配TbRestaurant呢

67,512

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧