Java 创建单例数组的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3582502/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:08:21  来源:igfitidea点击:

Best way to create singleton array

javaarrays

提问by Manuel Selva

What is the "easiest" way for you to create a singleton (with exactly one element) Objects array in Java ?

在 Java 中创建单例(只有一个元素)对象数组的“最简单”方法是什么?

采纳答案by KristofMols

Object [] singleton = { new SomeObject() };

回答by Sean Patrick Floyd

The standard way is this:

标准方法是这样的:

String[] arr = new String[]{"I am the one and only"};

I'm afraid it doesn't get much simpler than this.

恐怕没有比这更简单的了。

Edit: it does:

编辑:它确实:

String[] arr = {"I am the one and only"};

Thanks aioobe, I keep forgetting this.

谢谢aioobe,我一直忘记这个。



Of course if you often create array you can create a helper method that makes things a bit simpler:

当然,如果你经常创建数组,你可以创建一个帮助方法,让事情变得更简单:

public static <T> T[] asArray(T... items){
    return items;
}

String[] arr = asArray("I am the one and only");

(But you can't enforce at compile time that it will be an array with only one element)

(但你不能在编译时强制它是一个只有一个元素的数组)



Next I was going to write a singleton array method, but Stephen beat me to that.

接下来我要写一个单例数组方法,但斯蒂芬打败了我

回答by Stephen C

This should do the job

这应该可以完成工作

public SomeType[] makeSingletonArray(SomeType elem) {
    return new SomeType[]{elem};
}

A generic version of this method would be somewhat awkward to use, since you would need to pass it a Classobject as an additional parameter.

此方法的通用版本使用起来有些尴尬,因为您需要将一个Class对象作为附加参数传递给它。

Inlining the SomeType[]{elem}expression is simpler, and that's how I'd normally do this.

内联SomeType[]{elem}表达式更简单,这就是我通常这样做的方式。

回答by Nate W.

You could do this:

你可以这样做:

String[] a = Collections.singletonList("SingleElement").toArray();

String[] a = Collections.singletonList("SingleElement").toArray();

Edit:Whoops! The above example doesn't compile. As stated in the comment, this can be done either as:

编辑:哎呀!上面的例子不能编译。正如评论中所述,这可以通过以下方式完成:

Object[] a = Collections.singletonList("SingleElement").toArray();
Or
String[] a = Collections.singletonList("SingleElement").toArray(new String[1]);

Object[] a = Collections.singletonList("SingleElement").toArray();
或者
String[] a = Collections.singletonList("SingleElement").toArray(new String[1]);

回答by u290629

enum solution(anti reflect attack):

枚举解决方案(反反射攻击):

enum MySingleton{
    INSTANCE(new String[]{"a","b"});

    final String[] values;

    private MySingleton(String[] values) {
        this.values = values;
    }
}

reference it as:

将其引用为:

MySingleton.INSTANCE;

回答by Yoory N.

If your project is already using Apache Commons lib, you can stick to ArrayUtils.toArray()method.

如果您的项目已经在使用 Apache Commons lib,您可以坚持使用ArrayUtils.toArray()方法。

String[] arr = ArrayUtils.toArray("The string");
// or if using static import
String[] arr = toArray("The string");

Even if using static import it is still more verbose than the accepted answer:

即使使用静态导入,它仍然比接受的答案更冗长:

String[] arr = {"The string"};

But it comes very handy when compact array initializer syntax is not allowed.

但是当不允许使用紧凑数组初始值设定项语法时,它会非常方便。

Some examples:

一些例子:

someMethod(toArray("The string"), /* other params */);

return toArray("The string");

@DataProvider
public Object[][] someDataProvider() {
    return rangeClosed(-12, +12)
        .map(HOURS::toMillis).boxed()
        .map(ArrayUtils::toArray)
        .toArray(Object[][]::new);
}

You can imagine any other examples yourself.

您可以自己想象任何其他示例。

Also note, that the ArrayUtils.toArray()can wrap an arbitrary number of objects into array, not only a single one.

另请注意,ArrayUtils.toArray()可以将任意数量的对象包装到数组中,而不仅仅是一个。