63

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

1
  • 5
    You should know, that when using an array, the content is mutable. Consider using a singleton set usin Collections.singletonSet(element). Commented Aug 28, 2010 at 17:10

7 Answers 7

57
Object [] singleton = { new SomeObject() };
Sign up to request clarification or add additional context in comments.

1 Comment

Too bad this cannot be used without type annotation, e.g. you cannot pass the right part as function argument.
27

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.

2 Comments

"I'm afraid it doesn't get much simpler than this.". In that particular line, you may remove new String[] :-)
To be fair, the 'normal' notation really isn't that difficult.
14

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

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.

Comments

6

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;

1 Comment

The OP is asking not for a Singleton (as in an instance of the GOF pattern) but just for how to make an array with one element (also known as a singleton array in English like the singleton* methods in Collections). So, your {"a","b"} is not a singleton array (it has 2 elements) even though it is an instance of the Singleton pattern.
6

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.

Comments

3

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

1 Comment

Does not compile. Has to be either Object[] a = Collections.singletonList("SingleElement").toArray(); or String[] a = Collections.singletonList("SingleElement").toArray(new String[1]);
0

Arrays in Java are mutable.

But if you want to create a single object in an array, you can do like this:

Object[] objArray = new Object[] { put your object here };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.