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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 黑马任雪刚 中级黑马   /  2012-7-31 22:15  /  1545 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

//运用泛型交换一个数组中指定两个位置的值。
public class GenericDemo
{

       
        public static void main(String[] args)
        {
                int[] arr={1,2,3,4,5,6};
                demo(arr,2,3);//这句代码怎么老是报错呀?错误信息为:The method demo(T[], int, int) in the type GenericDemo is
                                                //not applicable for the arguments (int[], int, int))
                for(int i:arr)                                
                {
                        System.out.println(i);
                }

        }
        public static<T> void  demo(T[] arr,int post1,int post2)
        {
                T temp=arr[post1];
                arr[post1]=arr[post2];
                arr[post2]=temp;
        }

}

评分

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

查看全部评分

3 个回复

倒序浏览
  1. public class Test
  2. {

  3.         
  4.         public static void main(String[] args)
  5.          {
  6.                  Integer [] arr={1,2,3,4,5,6};//[color=Red]把int改成Integer就行了。因为基本数据类型的数组,传进去的话是数组,而与下面传进去的T[]arr不匹配。public static<T> void  demo(T[] arr,int post1,int post2)[/color]
  7.                  demo(arr,2,3);//这句代码怎么老是报错呀?错误信息为:The method demo(T[], int, int) in the type GenericDemo is
  8.                                                 //not applicable for the arguments (int[], int, int))
  9.                  for(int i:arr)                                 
  10.                 {
  11.                          System.out.println(i);
  12.                  }

  13.         }
  14.          public static<T> void  demo(T[] arr,int post1,int post2)
  15.          {
  16.                  T temp=arr[post1];
  17.                  arr[post1]=arr[post2];
  18.                  arr[post2]=temp;
  19.          }

  20. }
复制代码

评分

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

查看全部评分

回复 使用道具 举报
本帖最后由 王志明 于 2012-7-31 22:28 编辑

public static void main(String[] args) {
        // 这里要定义成包装类型的,也就是说泛型指定的是未确定的"类"类型,不能使用基本数据类型做泛型的参数
        Integer[] arr = { 1, 2, 3, 4, 5, 6 };
        demo(arr, 2, 3);// 这句代码怎么老是报错呀?错误信息为:The method demo(T[], int, int) in
                        // the type GenericDemo is
                        // not applicable for the arguments (int[], int, int))
        for (int i : arr) {
                System.out.println(i);
        }

}

public static <T> void demo(T[] arr, int post1, int post2) {
        T temp = arr[post1];
        arr[post1] = arr[post2];
        arr[post2] = temp;
}

评分

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

查看全部评分

回复 使用道具 举报
基础数据类型4类8种,不能作为泛型的参数,你转为相应的对象就没问题了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马