0

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[]?

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?

2
  • 4
    This is very poor design. What are you trying to do? Commented Jul 11, 2011 at 21:39
  • @Martel, sorry i was wrong. @SLaks, why you think this is poor design?? Commented Jul 11, 2011 at 23:30

4 Answers 4

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the details. I just realized my method also works. I don't know why it didn't initially.
2

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);

1 Comment

yes thanks, I just realized it works. I don't know initially i tried but always had this type error of casting.
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.

3 Comments

Why do you use System.err.println()?
Haha. Simpler keystrokes (I can use one finger to type err since e and r are side by side; out involves 2 fingers).
thanks, it is actually working. I did not know this strange problem with Eclipse, but now its' working:)))
1

You could use a wrapper:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.