The Artima Developer Community
Sponsored Link

Java Buzz Forum
How Do You Use Collection.toArray(Object[] a)?

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Weiqi Gao

Posts: 1808
Nickname: weiqigao
Registered: Jun, 2003

Weiqi Gao is a Java programmer.
How Do You Use Collection.toArray(Object[] a)? Posted: Aug 3, 2006 8:10 PM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Weiqi Gao.
Original Post: How Do You Use Collection.toArray(Object[] a)?
Feed Title: Weiqi Gao's Weblog
Feed URL: http://www.weiqigao.com/blog/rss.xml
Feed Description: Sharing My Experience...
Latest Java Buzz Posts
Latest Java Buzz Posts by Weiqi Gao
Latest Posts From Weiqi Gao's Weblog

Advertisement

I'm working on some Java code, using J2SDK 1.4. And I needed to turn a java.util.ArrayList of Foo objects into an array of Foo objects. So naturally I thought about java.util.Collection's

public Object[] toArray(Object[] a)

method. It's been a while since I last used this method. So I surfed over to the Javadoc at Sun's Java website. The first thing that jumped into my eyes is this code sample:

String[] x = (String[]) v.toArray(new String[0]);

That's exactly what I needed (and eventually what I did.) However something else caught my eyes too:

If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.

What that means is that if my List contains exactly three Foos, then I can either do:

Foo[] foos = (Foo[]) list.toArray(new Foo[0]);

or

Foo[] foos = new Foo[3];
list.toArray(foos);

to achieve the same result. The first alternative also works when we don't know the size of the List. The second alternative works only if I already know the size of the List. And the second way offers any advantage over the first only if the foos array can be reused in multiple toArray() calls. But if I know the size of the collection, I can probably avoid the use of List altogether.

How do you use Collection.toArray(Object[] a)? (I would really like to be educated about real world code where the second alternative wins over the first.)

Read: How Do You Use Collection.toArray(Object[] a)?

Topic: Esper 1.0 - Initial Release Previous Topic   Next Topic Topic: Remove Windows Genuine Advantage (Download Latest Version)

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use