Jeremy Stein - Brain

« »

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)

October 31, 2007 2 Comments.

2 Comments

  1. 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.

  2. Lev replied:

    I was looking for a similar solution and does exactly this.

    September 16th, 2013 at 10:23 am. Permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

Why ask?

« »