Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to convert single objects to an array?

Tags:

java

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;
}
like image 285
DivideByHero Avatar asked Jan 29 '09 03:01

DivideByHero


2 Answers

Why not simply:

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

What are you really trying to accomplish?

like image 99
yawmark Avatar answered Oct 05 '22 22:10

yawmark


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.

like image 28
Outlaw Programmer Avatar answered Oct 06 '22 00:10

Outlaw Programmer