A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 曹冬明 中级黑马   /  2014-4-21 21:34  /  715 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. import java.util.*;

  2. class GenericDemo
  3. {
  4.         public static void main(String[] args){
  5.                 copy1(new Integer[10],new String[10]);//为什么这一句就不报错呢,看了张老师的视频的解释,我理解困难
  6.                 copy2(new ArrayList<String>(),new Integer[10]);
  7.         }
  8.         private static <T> void copy1(T[] a, T[] b){
  9.                
  10.         }
  11.         private static <T> void copy2(ArrayList<T> a, T[] b){
  12.                
  13.         }
  14. }
复制代码

3 个回复

倒序浏览
本帖最后由 ⒈心只霸占沵 于 2014-4-21 22:04 编辑
  1. package Other;

  2. import java.util.*;


  3. class GenericDemo
  4. {
  5.         public static void main(String[] args){
  6.                 copy1(new Integer[10],new String[10]);//为什么这一句就不报错呢,看了张老师的视频的解释,我理解困难
  7.                 copy2(new ArrayList<String>(),new Integer[10]);
  8.         }  
  9.          private static <T> void copy1(T[] a, T[] b){
  10.              /*这个方法,当你copy1(new Integer[10],new String[10]);这样调用的时候第一个参数为Integer[]类型,第二个参数为String[]类型,他会向上提取,就会去Integer[]和String[]的并集也就是Object[],这里就是多态的体现
  11.              */
  12.         }
  13.         private static <T> void copy2(ArrayList<T> a, T[] b){
  14.                 /*这个方法,当你copy2(new ArrayList<String>(),new Integer[10]),这样调用就已经把T定位String类型, 因为如果是泛型定义类型是这样的话  List<T> list=new ArrayList<String>();这个T必须是String类型,如果是其他类型编译不通过,所以T已经被new ArrayList<String>(),这个实参固定了类型,只能为String,所以第二个参数传递的时候传递Integer就会报错
  15.                 */
  16.         }
  17. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
ily521125 + 1

查看全部评分

回复 使用道具 举报
copy1 方法的T 是可以理解成 都是  Object 而 copy2  则是 Integer  和  String   就成了  T  不是同一个类型了
回复 使用道具 举报

恩,明白了,是这么回事!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马