Search code examples
javaarraysobjectprimitive

java function that work with objects and primitives


I'm trying to write a function that accept an array and return an array in different order.

It works with int, double, string, object or any object in an array.

Follow are the sample of the function for String.

public String[] randomize(String[] array, int randomKey)
{
    //algorithm here
    return newStringArray;
}

For all the Object type, I know I can do it like

public Object[] randomize(Object[] array, int randomKey)
{
    //algorithm here
    return newObjectArray;
}

Instead of boxing all the primitive type into an object, is there any other method I can just write the algorithm once and without creating function for each primitive array? Is there a generic array type that work for objects AND primitive?

Thanks

P.S. Do not want to use autoboxing because of the performance penalty. Quote from [autoboxing]: http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code.


Solution

  • Sadly generics won't work here as generics do not cover primitives but they do cover primitive arrays. Primitive arrays are also not autoboxed into a wrapper class array. That is something you would have to do manually, but that is very very slow. One solution is to provide an override for each primitive, similar to how Arrays.sort is implemented. This creates a lot of duplicate code. Another solution is to use an Array interface similar to ArrayList that emulates an Array, get/set methods for indices, and provide subclasses for each primitive and one for objects. You can then use the Array interface and not care what the actual type is.