Utility method for wrapping an object in a collection

I'm looking for a static method in the Java core libraries or some other commonly used dependency — preferably one of Apache — that does the following:

public static <T> Collection<T> wrap(final T object){
    final Collection<T> collection = new ArrayList<T>();
    collection.add(object);
    return collection;
}

Do you know where such a method already exists? Since I guess the problem is common, I don't want to duplicate it's solution.

Answers


java.util.Collections.singleton(object) will give you an immutable Set. singletonList is also available.

Less efficiently java.util.Arrays.asList(object) will give you a mutable (can use list.set(0, x);), but non-structurally changeable (can't add or remove) List. It is a bit more expensive as there is an extra array that is created client-side.


Need Your Help

How to add shadow on NSSearchField

osx shadow nssearchfield

I want to overwrite the NSSearchField class and make it seems like

Android Service won't start from a Thread

android android-service

I am trying to start a service from a thread which I hava initialized with getApplicationContext() but context.startService returns null. I can't figure out why.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.