how to cast object to double type array in java?
OK 开发者_StackOverflow中文版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[]?
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[] . Use getters to access them.
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.
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);
Not sure why you're having difficulty: on Java 6 this works as expected.
Try compiling this class and running it:
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.
You could use a wrapper:
Integer[] array = (Integer[]) myTest()
精彩评论