Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How do I instantiate and initialize an ArrayList in a single line of code?

807603Oct 16 2007 — edited Oct 17 2007
Please pardon my stupidity, but is there a way to do this?

The javadocs say you can pass a Collection<E> to an ArrayList<E> constructor, but Collections appear to be constructed in the same manner. It seems I have to use the add method x number of times if I don't have a Collection of data already. What I'm looking for is something like the old array constructor that would let you do this:

private static final Object[] primaryColors = new Object[] {"Red", "Blue", "Yellow"};

In other words, is there a way to do something like this? (Of course this sample doesn't compile.)

private static final ArrayList<String> primaryColors = new ArrayList<String>(new String[3]{"red", "blue", "yellow"});
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 14 2007
Added on Oct 16 2007
19 comments
1,693 views