注册 登录
编程论坛 JAVA论坛

为什么这里出错了?

msl12 发布于 2015-11-08 12:47, 1311 次点击
代码如下:
------------------------------------------------------------------------
import java.lang.reflect.Array;
import java.util.*;

public class Test12 {
    public static void main(String args[]) throws Exception {
        int temp[] = { 1, 2, 3 };
        int newTemp[]=(int [])arrayInc2(temp, 5);
        System.out.print(Arrays.toString(newTemp));
    }
   
    public static Object arrayInc2(Object obj, int len) {
        Object newO=new Object[len];
        int co=Array.getLength(obj);
        System.arraycopy(obj, 0, newO, 0, co);
        
        return newO;
    }
}
8 回复
#2
诸葛欧阳2015-11-08 16:13
这样写啥意思?
#3
msl122015-11-08 22:49
回复 2楼 诸葛欧阳
想要把数组扩大的效果
#4
林月儿2015-11-09 11:07
public static Object arrayInc2(Object obj, int len)
方法的返回值类型前后不一致
程序代码:
public class Test12 {
    public static void main(String args[]) throws Exception {
        int temp[] = { 1, 2, 3 };
        int newTemp[]=(int [])arrayInc2(temp, 5);
        System.out.print(Arrays.toString(newTemp));
    }
   
    public static int[] arrayInc2(int[] obj, int len) {
        int[] newO=new int[len];
        int co=Array.getLength(obj);
        System.arraycopy(obj, 0, newO, 0, co);
        
        return newO;
    }
}
#5
msl122015-11-09 13:02
回复 4楼 林月儿
所以我不是已经强制转换了么?
#6
msl122015-11-09 13:03
回复 4楼 林月儿
其实我想利用反射机制来完成的,能不能不改成int?
#7
林月儿2015-11-09 14:07
倒不如按泛型改。。。
#8
calix2015-11-09 15:14
如果只是“扩充”数组容量
ArrayList.ensureCapacity
AbstractStringBuilder.expandCapacity
...
都有类似的实现,可以参考下
#9
GrayJerry2015-11-25 16:09
Object newO=new Object[len];    newO被定义成object数组
int newTemp[]=(int[])arrayInc2(temp, 5);    newO不能转为int[]数组

下面的代码可以:
public class Test12 {
    public static void main(String args[]) throws Exception {
        int temp[] = { 1, 2, 3 };
        int newTemp[]=(int[])arrayInc2(temp, 5);
        System.out.print(Arrays.toString(newTemp));
    }
   
    public static Object arrayInc2(Object obj, int len) {
        Object newO=new int[len];
        int co=Array.getLength(obj);
        //int[] s = (int[])obj;
        System.arraycopy(obj, 0, newO, 0, co);
        
        return newO;
    }
}
1