Problem using splice() on non-primitive input
in
Programming Questions
•
11 months ago
I can only get the splice() function to work with arrays of primitive types (char, int, etc.) and String arrays.
Whenever I use splice() on arrays of objects of any other classes, even those from Processing (like PVector and PImage), I run into the problem that splice() returns an Object instead of an Object[]. For some reason, it is not allowed to cast this Object to the appropriate array type (e.g. PVector[]).
Attempting similar array operations using the subset() and concat() functions works just fine, even though these functions also return an Object when you pass them arrays of non-primitive types.
For a bit of context, I am using Eclipse instead of the standard Processing editor. In the examples below, I do not initialize the individual elements of the arrays (thus they are filled with null values), but I have tested both with and without initialization, and it makes no difference. Therefore, I have removed the element-by-element initialization from the examples in the interest of brevity.
Example 1: (Does not work. Compiles and runs, but throws a ClassCastException when splice() is invoked)
PVector[] a = new PVector[100];
PVector[] b = new PVector[100];
a = (PVector[])splice(a,b,a.length); //Insert b at the end of a
Example 2: (Works just fine; throws no exceptions)
PVector[] a = new PVector[100];
PVector[] b = new PVector[100];
a = (PVector[])concat(a,b); //equivalent to the output of splice() as used in Example 1
Example 3: (Works just fine; throws no exception)
int[] a = new int[100];
int[] b = new int[100];
a = (int[])splice(a,b,a.length); //When the type is primitive, splice() works without issue
Example 4: (Works. However, c cannot be recast to an array type.)
PVector[] a = new PVector[100];
PVector[] b = new PVector[100];
Object c = splice(a,b,a.length); //The output can be stored in an Object, but cannot be recast to any kind of array, making the output useless
Questions:
1) Why does recasting the output of splice() fail, when doing the same with concat() and subset() succeeds?
2) Why are all of the above designed to return a simple Object instead of an Object[], when invoked with a custom class. It would seem more natural for an array manipulation method to return an array instead of a single object?
I'd appreciate any illumination of this issue, even if it does not solve the problem.
Thanks!
2