From: Lew Newsgroups: comp.lang.java.programmer Subject: Re: create an ArrayList + add a first element and return the List in ONE statement possible ? Date: Thu, 27 Jan 2011 15:17:50 -0500 Organization: albasani.net Lines: 43 Message-ID: References: <4d41923c$0$6766$9b4e6d93@newsspool3.arcor-online.net> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.albasani.net hMoD7PWQcxOKaUA9p6qdK32ai4EwibuZOQfvcOU0KG24qgPcNrxwIDSTx1v9IwoCilt+WZoJmhOQaY23wKgE0wyWbM8PwOW8DmrqRvTXtoUeOvoTnDHQR5HCSspmYLkU NNTP-Posting-Date: Thu, 27 Jan 2011 20:15:19 +0000 (UTC) In-Reply-To: Cancel-Lock: sha1:lI8DqZ/G/RYjFTK4DcLgKgppUmg= User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101208 Thunderbird/3.1.7 Injection-Info: news.albasani.net; logging-data="k4Tl0rIbw6hCl5hev91BU6KIIYFDfitGQV4JEBi5feAUJaGj10HNGok2mhSy1NZ41hkrxe9/O1O54ZbXiubEdPQzoBvOUdIQR/VJpTRt27nkAacwIMwqwIFaqAkdTu8v"; mail-complaints-to="abuse@albasani.net" Path: csiph.com!eeepc.pasdenom.info!news.pasdenom.info!news.dougwise.org!feed.ac-versailles.fr!usenet-fr.net!de-l.enfer-du-nord.net!feeder1.enfer-du-nord.net!weretis.net!feeder4.news.weretis.net!news.albasani.net!not-for-mail Xref: csiph.com comp.lang.java.programmer:26203 Robin Wenger wrote: >> 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 lObj = new ArrayList(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? Why is it a problem to split it into separate statements? Ian Pilcher wrote: > There are lots of ways, including: > > ArrayList lObj = new ArrayList( > Collections.singleton(new Object77())); The declared type should probably be 'List'. The Javadocs might also lead one to: List lObj = new ArrayList ( Arrays.asList( new Object77() )); or, if you aren't particular about the implementation: List 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 -- Lew Ceci n'est pas une pipe.