1



i created a class derived of Object and I have a object array.
how to do cast object array to my class array?

public class CastArray{

public CastArray(){
}

public long toLong(){
    return Long.parseLong(this.toString());
}    

public double toDouble(){
    return Double.parseDouble(this.toString());
}

public int toInteger(){
    return Integer.parseInt(this.toString());
}
}<br />

return Error:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LBasic.CastArray;

1
  • 2
    In java you don't need to explicitly write "extends Object". Commented Nov 5, 2011 at 6:42

3 Answers 3

3

The question is a bit vague but let me make an attempt to answer it. if the object array is actually an array of your class, you can do a direct cast to your array e.g. A[] a = (A[]) objArray;. Alternatively, if you know that each element can be cast into your class (is an instance of your class or one of its sub classes), you can clone it by creating a new array and adding each element with a cast to your class. e.g.:

A[] a = new A[objArray.length];
int i = 0;
for (Object o : objArray) {
   a[i++] = (A) o;
}
Sign up to request clarification or add additional context in comments.

1 Comment

this is how it's done System.arrayCopy(objArray, 0, a, 0, a.length)
1

It sounds like you're asking how to do this:

Object[] objectArray = {};

CastArray castArray = (CastArray)objectArray;

If this is the case you can't.

1 Comment

Well one could do something like this: Badge[] badges = (Badge[]) clazz.cast(Array.newInstance(clazz.getComponentType(), 0));
1

The Arrays.copyOf(...) could be a solution for you.

Best regards!

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.