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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 黑马无敌 中级黑马   /  2015-6-30 11:03  /  2656 人查看  /  9 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

2黑马币
  1. public class Test1 {
  2.         @Test
  3.         public void test(){
  4.                 int arr[] = {1,2,3,4,5,6,7,8,9};
  5.                 reverse(arr);
  6.         }

  7.        
  8.        
  9.         //编写一个泛型方法,实现数组反转
  10.         public <T> void reverse(T arr[]){
  11.                 int start = 0;
  12.                 int end = arr.length-1;
  13.                 while(start<end){
  14.                        
  15.                         T temp = arr[start];
  16.                         arr[start] = arr[end];
  17.                         arr[end] = temp;
  18.                        
  19.                         start++;
  20.                         end--;
  21.                 }
  22.         }
  23. }
复制代码


QQ图片20150630110343.png (875 Bytes, 下载次数: 13)

QQ图片20150630110343.png

最佳答案

查看完整内容

int改成Integer,泛型是针对对象的,不是针对基本数据类型,需要自动提升一下

9 个回复

倒序浏览
int改成Integer,泛型是针对对象的,不是针对基本数据类型,需要自动提升一下
回复 使用道具 举报
public class test1 {

        public void test() {
                int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                reverse(arr);
        }

        // 编写一个泛型方法,实现数组反转
        public <T> void reverse(int[] arr) {
                int start = 0;
                int end = arr.length - 1;
                while (start < end) {

                        int temp = arr[start];
                        arr[start] = arr[end];
                        arr[end] = temp;

                        start++;
                        end--;
                }
        }
}
这样就不会报错了
回复 使用道具 举报
彬彬有理 发表于 2015-6-30 11:25
public class test1 {

        public void test() {

我就是要定义一个泛型,你这样把泛型去掉了,就违背题目意思了,

不过我已经解决了这个问题了。。。
回复 使用道具 举报
没有实现 reverse方法
回复 使用道具 举报
你的T是泛型默认的Object类,而你转换的的时候用的是int类型去接收的,int是基本类型,不可以用T这样的泛型,Int改成interge自动包装类型
回复 使用道具 举报
逸舟213 来自手机 中级黑马 2015-7-1 21:38:06
7#
问题很好!
回复 使用道具 举报
学习啦:lol
回复 使用道具 举报
学习一下
回复 使用道具 举报
这个问题我不会啊
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马