Sponsored Links

Ad by Google
If you came here from google or direct link you must have to read my previous post BFSI-domain:What is the different between ArrayList and LinkedList?

Ok now lets start with a smart answer:

Performance is always matter, If your business requirement is fast iteration of element based on index for example get(index) then must go with ArrayList
Or If your business requirement is fast random insertion/deletion then must go with LinkedList.

But if your interviewer says, that he does not want to fast random insertion/deletion of element or fast iteration of element based on index, he just want to store 10 million of element inside a collection between ArrayList and LinkedList. Most of the time candidate get fail to give the correct answer of this because candidates start comparing between insertion/deletion/iteration only.
Most of the candidate forgot to comparing them about there internal structure(how they keep the elements) and fail to give the correct answer, but most of the smart candidates always find a fruitful discussion on this topic.

Well answer of this question is yes ArrayList, Ok How?

Point #1 Regarding Space: Well ArrayList will take less memory as compared to LinkedList because we all know that LinkedList maintain doubly Linked-List so LinkedList require extra space to keep the next and previous elements.

Point #2 Regading Time: We all know that ArrayList has a constructor with initialCapacity

public ArrayList(int initialCapacity)

which will again reduce the insertion time of large number of elements. At the time of of ArrayList declaration, declared with initial capacity because you all ready know how much element you want to store and this is what a interviewer wants from you.

For practical try to run this program and compare the time required by each ArrayList and LinkedList

public static void main(String[] args)  {
   List<Long> longList = new LinkedList<>();
   // remove comment from  below line and add comment on above line
   //List<Long> longLis = new ArrayList<Long>(10000000);
   long maxValue = 10000000;

   long startTime = System.currentTimeMillis();

   for (long l = 0; l < maxValue; l++) {

   long endTime = System.currentTimeMillis();

   System.out.println(endTime - startTime);

Few very popular java interview questions:
What are the key differences between Comparable and Comparator.
Serializable Vs Externalizable.
Java program to find missing numbers
Why String is Immutable in java
Java program to create your own ArrayList

Don't forgot to post your comments/feedback/suggestion about this post or if you have something to add on this.
Sponsored Links


Post a Comment