Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!.POSTED!not-for-mail From: Jan Burse Newsgroups: comp.lang.java.programmer Subject: Re: setSize ArrayList, when will it come? Date: Wed, 10 Aug 2011 00:36:03 +0200 Organization: albasani.net Lines: 50 Message-ID: References: <1eadnROad6gX8NzTnZ2dnUVZ_tydnZ2d@earthlink.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.albasani.net I9YqJFKz4u3UC9EdNUaDr/0uu8Ad7d4t+7Qj6IY9LblG71GgqfHM/hKNOH8GfDmdqdedtM0h7VycvIdot8RZHg== NNTP-Posting-Date: Tue, 9 Aug 2011 22:36:06 +0000 (UTC) Injection-Info: news.albasani.net; logging-data="ezuHTEoTejDN2slpWHZhu75QPZsN3BDhg4BAlc/fqR9MFdrQxnQLc2qh/vvh2OBZu4Jpp1PRgAIlbQnKdZNZQOq3NSm+u6xrTxppX4Kz57ZukD5Szn7mgc1xkKnXcWO3"; mail-complaints-to="abuse@albasani.net" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20110706 Firefox/5.0 SeaMonkey/2.2 In-Reply-To: Cancel-Lock: sha1:nhdSzyjHq0vg8XkcPNqqOwdHVEA= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:6930 Tom Anderson schrieb: > On Tue, 9 Aug 2011, Patricia Shanahan wrote: > >> On 8/9/2011 9:58 AM, Roedy Green wrote: >> ... >>> Further, I would hope ArrayList.addAll would be smart enough to grow >>> the array only once, if needed. >> ... >> >> It does the following: >> >> 1. Grow to the needed size. >> >> 2. Call the other collection's toArray method. >> >> 3. System.arraycopy the toArray result into the ArrayList's elementData. >> >> This double copy is going to be faster than the one at a time approach >> only if large numbers of nulls are being added. If that is the case, >> the structure is probably too sparse for ArrayList to be a good choice. > > It would be nice if ArrayList used a loop to do the copy for small added > collections; it could cut over to the array method for larger addends. > > Anyway, with List.addAll and Collections.nCopies, we can write: > > void setSize(List list, int size) { > int change = size - list.size(); > if (change > 0) { > list.addAll(Collections.nCopies(change, null)); > } > else if (change < 0) { > list.subList(size, list.size()).clear(); > if (list instanceof ArrayList) ((ArrayList)list).trimToSize(); > } > // else do nothing > } > > I haven't tried that, but it should work. > > So, Jan, less whining, more coding, please. > > tom > This is not efficient. You don't get it what the problem is. I really really need a highly efficient setSize() specialized, otherwise my stuff will not work.