Jeremy Stein - Brain
« Resize Google toolbar search box | Ubuntu laptop screen resolution » |
Create a list of one item in Java
Sometimes you need to call a method that takes a collection, but you just want to send it one value. You wish you didn’t have to do this:
List tempList = new ArrayList<MyClass>(1); tempList.add(value);
You can do it all in one expression. Here is a Java idiom for creating a collection with a single item in it:
Arrays.asList(new MyClass[] {value})
In Java 1.5 you can simplify that to:
Arrays.asList(value)
2 Comments
- Jos replied:
Works great, but… returns a java.util.Arrays.ArrayList, not java.util.ArrayList, published as a List. This will usually go unnoticed, until you get an OperationNotSupportedException when you do remove() on the iterator() you got from the resulting List.
In cases you or whoever uses your code may want to use that list to remove elements later, build a List who’s iterator does support remove().November 22nd, 2012 at 11:54 am. Permalink.
- Lev replied:
I was looking for a similar solution and does exactly this.
September 16th, 2013 at 10:23 am. Permalink.
« Resize Google toolbar search box | Ubuntu laptop screen resolution » |
Leave a Reply