Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to copy one array list to another

Tags:

java

arraylist

I came across a question related to ArrayList of java in a company written test. My query is just a small part of the actual question.

Lets say we have the following function to copy one ArrayList to another:

void function(List<E> l)
{
    List<E> m = new ArrayList<E>(l);
}

The question basically asks to optimize this copy operation. The List may contain a million entries. I have tried the following approaches:

Collections.copy

System.Arraycopy

addAll

But all of these seem to be slower than the given method. I need a method that is faster than the given method or is it the best method that is available?

like image 309
Rohan Bhalla Avatar asked Nov 04 '13 17:11

Rohan Bhalla


People also ask

How do I copy one ArrayList to another?

In order to copy elements of ArrayList to another ArrayList, we use the Collections. copy() method. It is used to copy all elements of a collection into another. where src is the source list object and dest is the destination list object.

How do you copy an ArrayList?

The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList. Syntax: public Object clone(); Return Value: This function returns a copy of the instance of Object.

How do you copy an array to an ArrayList?

We can convert an array to arraylist using following ways. Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.

Which ArrayList is faster than others?

LinkedList is faster than ArrayList while inserting and deleting elements, but it is slow while fetching each element.


1 Answers

Well Firstly I think there is a benchmark error. public ArrayList(Collection<? extends E> c) uses Arrays.copyOf which internally uses System.arraycopy (Source here). Hence System.arraycopy or addAll cannot be slower than your mentioned code.

For the question, there cannot be a faster way (given you wish to not loose the type information, that might save clock cycles but very trivial) as the operation will have to be O(n). And System.arraycopy is the fastest way out there given it uses native calls to copy them fast.

like image 135
Jatin Avatar answered Sep 24 '22 21:09

Jatin