java 将单个对象转换为数组的函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/490424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Function to convert single objects to an array?
提问by DivideByHero
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;
}
回答by yawmark
Why not simply:
为什么不简单:
Object o = new Object();
Object[] array = { o }; // no method call required!
What are you really trying to accomplish?
你真正想要完成什么?
回答by Outlaw Programmer
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:
在有时我想传递单个对象但有时我想传递数组的情况下,通常我只是在 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.
可以使用可变参数,但前提是数组是最后一个参数。
回答by Lawrence Dol
Assuming you need a that you need an array that is properly typed, you can use java.lang.reflect.Array:
假设您需要一个类型正确的数组,您可以使用 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
}

