tags:

views:

137

answers:

5

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

+2  A: 

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.


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.

seanizer
"I'm afraid it doesn't get much simpler than this.". In that particular line, you may remove `new String[]` :-)
aioobe
To be fair, the 'normal' notation really isn't that difficult.
Joeri Hendrickx
@aioobe added that change, thanks
seanizer
+5  A: 
Object [] singleton = { new SomeObject() };
Molske
+2  A: 

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 Class object as an additional parameter.

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

Stephen C
A: 

You could do this:

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]);

Shakedown
Does not compile. Has to be either `Object[] a = Collections.singletonList("SingleElement").toArray();` or `String[] a = Collections.singletonList("SingleElement").toArray(new String[1]);`
seanizer
+1  A: 

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;
卢声远 Shengyuan Lu
+1 for the correct way to make a true singleton on the JVM
gpampara