tags:

views:

174

answers:

3

I wanted to write a function that would take an object and convert it to an array that contains that object as a single element. It occurred to me that I could maybe do this with generics and variable arguments to essentially do this automatically, without the need to write a function for each object type I wished to use. Will this code work? Are there any subtleties I need to be aware of?

public static <X> X[] convert_to_array(X... in_objs){
    return in_objs;
}
+7  A: 

Why not simply:

Object o = new Object();
Object[] array = { o }; // no method call required!

What are you really trying to accomplish?

yawmark
+2  A: 

It works but it seems like:

 Object o = new Object();
 someMethod(new Object[] { o } );

is a little more straightforward then:

Object o = new Object();
someMethod(convert_to_array(o));

In cases where sometimes I want to pass a single object, but other times I want to pass an array, usually I just use an overloaded method in the API:

public void doSomething(Object o)
{
    doSomething(new Object[] { o } );
}

public void doSomething(Object[] array)
{
    // stuff goes here.
}

Varargs can be used but only if the array is the last parameter of course.

Outlaw Programmer
A: 

Assuming you need a that you need an array that is properly typed, you can use java.lang.reflect.Array:

static public Object[] createTypedArray(Object elm) {
    Object[] arr=(Object[])java.lang.reflect.Array.newInstance(elm.getClass(),1);
    arr[0]=elm;
    return arr; // this can be cast safely to an array of the type of elm
    }
Software Monkey