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?
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.
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.
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.
LinkedList is faster than ArrayList while inserting and deleting elements, but it is slow while fetching each element.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With