create an ArrayList + add a first element and return the List in ONE statement possible ?

R

Robin Wenger

As the subject said I wonder whether there is really no one-liner for creating an ArrayList + assign of the first element +
return the new list. I have expected the following to work in such a way but it does NOT work:

Object77 oneObject = new Object77();
ArrayList<Object77> lObj = new ArrayList<Object77>(oneObject);

The following returns a boolean and not the desired List:

boolean success = (new ArrayListObject77>()).add(oneObject);

Any other ideas?
Or do I really have to split this simple operation into separate statements?

Robin
 
I

Ian Pilcher

As the subject said I wonder whether there is really no one-liner for creating an ArrayList + assign of the first element +
return the new list. I have expected the following to work in such a way but it does NOT work:

Object77 oneObject = new Object77();
ArrayList<Object77> lObj = new ArrayList<Object77>(oneObject);

The following returns a boolean and not the desired List:

boolean success = (new ArrayListObject77>()).add(oneObject);

Any other ideas?
Or do I really have to split this simple operation into separate statements?

There are lots of ways, including:

ArrayList<Object77> lObj = new ArrayList<Object77>(
Collections.singleton(new Object77()));
 
L

Lew

Why is it a problem to split it into separate statements?

Ian said:
There are lots of ways, including:

ArrayList<Object77> lObj = new ArrayList<Object77>(
Collections.singleton(new Object77()));

The declared type should probably be 'List<Object77>'.

The Javadocs might also lead one to:

List <Object77> lObj = new ArrayList <Object77>
( Arrays.asList( new Object77() ));

or, if you aren't particular about the implementation:

List <Object77> lObj = Arrays.asList( new Object77() );

which saves a copy operation.

As Ian said, there are many ways. Know thy API. The study of the collections
types is especially rewarding.

http://download.oracle.com/javase/tutorial/collections/index.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,163
Latest member
Sasha15427
Top