铸造基本类型数组中的java对象数组 [英] Cast primitive type array into object array in java

查看:104
本文介绍了铸造基本类型数组中的java对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我无法在java中这样做吗?

Why I cannot do this in java?

Object[] o = (Object[])(new int[]{0,1,2,3.14,4});

我有接收对象的方法,然后再presents它作为一个字符串,但根据他的类型(原始,原始包装,阵列等)。当我创建一个单元测试,我经过一个数组的目标这是好的,但是当我执行对象的投进去的对象[] 我收到< STRONG> ClassCastException异常。
这是只与原始类型数组发生。有什么办法避免这种行为呢?如果没有,可能有人解释什么是对Java虚拟机这种现象的原因。

I have a method that receives an object and then represents it as a string, but depending on his type (primitive, primitive wrapper, array, etc...). When I was creating a Unit test, I was passing an array as Object which is Ok, but when I perform cast of that object into Object[] I'm getting ClassCastException. This is only happening with primitive type arrays. Is there any way to avoid this behavior? If not, could someone explain what is the reason of this behavior on Java Virtual Machine.

任何帮助是非常AP preciated。

Any help is very appreciated.

推荐答案

原始类型不能以这种方式进行改造。
你的情况,存在重复值的数组,3.14原因。
这将工作:

Primitive type cannot be transformed in this way. In your case, there is an array of double values, cause of 3.14. This will work:

    List<Object> objectList = new ArrayList<Object>();
    objectList.addAll(Arrays.asList(0,1,2,3.14,4));

即使是这样工作的:

Even this works :

List<Object> objectList = new ArrayList<Object>();
objectList.addAll(Arrays.asList(0,"sfsd",2,3.14,new Regexp("Test")));
for(Object object:objectList)
{
    System.out.println(object);
}

更新
好了,那里还有有人说,没有投基本数组将Object []直接的方式。
如果您希望将任何数组中字符串的方法,我可以建议这样

UPDATE Ok, there as there was said, there is not direct way to cast a primitive array to an Object[]. If you want a method that transforms any array in String, I can suggest this way

public class CastArray {

    public static void main(String[] args) {
        CastArray test = new CastArray();
        test.TestObj(new int[]{1, 2, 4});
        test.TestObj(new char[]{'c', 'a', 'a'});
        test.TestObj(new String[]{"fdsa", "fdafds"});
    }

    public void TestObj(Object obj) {
        if (!(obj instanceof Object[])) {
            if (obj instanceof int[]) {
                for (int i : (int[]) obj) {
                    System.out.print(i + " ");
                }
                System.out.println("");
            }
            if (obj instanceof char[]) {
                for (char c : (char[]) obj) {
                    System.out.print(c + " ");
                }
                System.out.println("");
            }
            //and so on, for every primitive type.
        } else {
            System.out.println(Arrays.asList((Object[]) obj));
        }
    }
}

是的,这很烦人写每一个原始类型的循环,但没有别的办法,恕我直言。

Yes, it's annoying to write a loop for every primitive type, but there is no other way, IMHO.

这篇关于铸造基本类型数组中的java对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆