Keith Devens .com |
Tuesday, December 2, 2008 | ![]() |
| A Lisp programmer knows the value of everything, but the cost of nothing. – Alan Perlis | ||
|
| ← Ned Batchelder: Object reference not set to an instance of an object | The World's Ugliest Car, restored → |

B. K. Oxley (binkley) (http://binkley.blogspot.com) wrote:
Madhusudhan Rao (http://jroller.com/page/madwho) wrote:
I usually have the following utility to create lists
public abstract class Utils {
public static <T> List<T> list(T... elements) {
final List<T> result = new ArrayList<T>();
for (T element : elements) {
result.add(element);
}
return result;
}
}
Usage:
final List<String> coffees = Utils.list("mocha", latte");
Keith (http://keithdevens.com/) wrote:
Cool, thanks. I wonder how much more efficient that is, if any, than the above:
new ArrayList<Foo>(Arrays.asList(foo));
Also, may I recommend a small change:
final List<T> result = new ArrayList<T>(elements.length);
for obvious reasons.
Feel free to post a comment below. Please see my comment policy.
Formatting Rules (No HTML):
Generated in about 0.263s.
(Used 8 db queries)

You might also chose to mention the Collections class with static methods such as addAll(...), the helpful public static members EMPTY_LIST, et al, and most on point for your code example, singletonList(T). Thus:
Arrays.asList(foo);
Becomes:
Collections.singletonList(foo);
Which to me seems to document better the intention of the code. However, the returned list is indeed a singleton: you cannot later modify it, so that may violate the contract of the surrounding method for the code fragment.