File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion 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: 15101

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
It's not a secret anymore!