简体   繁体   English

如何将 object 转换为 java 中的双精度型数组?

[英]how to cast object to double type array in java?

OK so what if i have a method like:好的,如果我有这样的方法怎么办:

Object[] myTest(int[] a, double[] b){
   return new Object[]{a,b};
}

Now How can i cast the result Object to int[] and double[]?现在如何将结果 Object 转换为 int[] 和 double[]?

Like if i use:就像我使用:

int[] array1 = (int[]) myTest(a,b)[0];
double[] array2 = (double[]) myTest(a,b)[1];

But this does not work.但这不起作用。 Or is there any efficient method to do this job?或者有什么有效的方法来完成这项工作?

Have a WrapperObject that contains int[] and double[].有一个包含 int[] 和 double[] 的 WrapperObject。 Use getters to access them.使用 getter 访问它们。

public class WrapperObject {

     private int[] a;
     private double[] b;

     public void setA(int[] a1) {
         a = a1;
     }

     public int[] getA() {
         return a;
     }
    .....
}

Let your myTest method return that object.让您的 myTest 方法返回 object。

public WrapperObject myTest(int[] a , double[] b) {
      return new WrapperObject(a, b);
}

Although your code is working fine with me, but you could do it in another way:虽然你的代码对我来说很好,但你可以用另一种方式来做:

public static Object myTest(int[] a, double[] b, int index)
{
    Object[] obj = {a,b};
    return obj[index];
}

Then use it like:然后像这样使用它:

int[] array1 = (int[]) myTest(a,b,0);
double[] array2 = (double[]) myTest(a,b,1);

You could use a wrapper:您可以使用包装器:

Integer[] array = (Integer[]) myTest()

Not sure why you're having difficulty: on Java 6 this works as expected.不知道您为什么遇到困难:在 Java 6 上,这可以按预期工作。

Try compiling this class and running it:尝试编译这个 class 并运行它:

public class t1
{
    public static void main(String[] args) throws Exception
    {
    int[] a = new int[1];
    double[] b = new double[1];

    int[] array1 = (int[]) myTest(a,b)[0];
    double[] array2 = (double[]) myTest(a,b)[1];
    System.err.println(array1);
    System.err.println(array2);
    }

    static Object[] myTest(int[] a, double[] b){
    return new Object[]{a,b};
    }
}

it will print out它会打印出来

[I@3e25a5
[D@19821f

That's the autoboxing taking place, but will still work.这就是发生的自动装箱,但仍然可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM