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;
}
Why not simply:
Object o = new Object();
Object[] array = { o }; // no method call required!
What are you really trying to accomplish?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With