This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Java in General and the fly likes Performance issue Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Performance issue" Watch "Performance issue" New topic

Performance issue

Patrick Mugabe
Ranch Hand

Joined: Jan 08, 2002
Posts: 132
If I have a list and I need to return an array what would execute faster:
1) converting it an array OR
2) converting it to an iterator
as in:

String [] out = new String[list.size()];
for(int i =0;i <out.length;i++){
out[i] = list.get(i);

Iterator iter = null;
int ctr = 0;
list = iter.iterator();
out[ctr++] =;

then I return an array
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15036

Write a small test program yourself to find out...

Note that interface List has a method toArray(...) to convert a List to an array. You don't need to do it "by hand".

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
As the previous poster said, you should not do this "by hand", but should use toArray() method.

However, if you were to do something like this "by hand", the right approach would depend on the exact type of List. An ArrayList will give slightly better performance using get(int index), whereas a LinkedList will give much better performance using Iterator. Using get(int index) on a large LinkedList will be seriously slow: O(n^2), I think.

If you do not know the actual exact type of List, it is best to use an Iterator.

In Java 5+, you can and should use "enhanced for" loop.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
I agree. Here's the link:
subject: Performance issue
jQuery in Action, 3rd edition