Reputation: 1218
I'm making a Java function randomize which gets one argument, an array of Objects.
Basically, this function randomizes the entire array and since the type of data isn't relevant, the method signature is: public static Object[] randomize(Object[] array)
.
However, this doesn't work for arrays of int, double etc.. (so for arrays of primitives). How can I get this to work? I don't want to have one function for objects and 8 overloaded functions for each of the primitive types. I can accept if there is one function for Object arrays and one function for ALL of the primitive types. How can I do this?
Thank you, Héctor
Upvotes: 0
Views: 110
Reputation: 122439
It is possible to write a method that will operate on primitive arrays and reference arrays alike without duplicating code. However, you will lose type safety. The method will take and return Object
since that's the only supertype of primitive arrays and reference arrays:
public static Object randomize(Object array) {
Then, inside the method, you can use the methods from the java.lang.reflect.Array
class to perform operations on the array. You would use Array.get()
, Array.set()
, Array.length()
on the array instead of the array access operators and length field. These methods work for both primitive arrays and reference arrays transparently. If you need to create a new array with the same runtime class as the old one, you can use Array.newInstance()
with the runtime component type from the passed-in array:
Array.newInstance(array.getClass().getComponentType(), N)
Upvotes: 1
Reputation: 23552
As a last resort, you can declare the method using Object as argument for the array and then check the type at runtime. Then you can determine and cast the array type in the method or use some other util library to do it for you.
Upvotes: 0
Reputation: 109547
The algorithm could create a permutation of the indices.
Some operations like Arrays.sort
are already available on a generic base.
But in general can only use reflection, which is costly, when not manipulation xxx[]
.
int[] intArray = new int[10];
randomize(intArray);
void randomize(Object array) {
if (array == null || array.getClass().isArray()) {
throw new IllegalArgumentException();
}
... use reflection
}
Upvotes: 1
Reputation: 36
As you said int is a primitive not an Object, so what you can do is use (for example) Integer (wrapper class for int) to build the array of ints, this however would require you to do so before you call that method. You can search for wrapper classes to get all the classes you need.
Upvotes: 0