创建单例数组的最佳方式

2022-08-31 19:50:42

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


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

答案 2

标准方式是这样的:

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

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

编辑:它做:

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

谢谢aiioobe,我一直忘记这一点。


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

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

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

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


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