• Post Reply Bookmark Topic Watch Topic
  • New Topic

regarding List  RSS feed

 
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If we have 1000 elements in our list and we want to add or delete some elements very often,which among LinkedList or ArrayList will be better.
Positive point of arrayList : After addition and deletion of element,we do not have to care about position of rest of the elements because that is automatically adjusted.
Negative Point of ArrayList : If we are adding an element at first place,we have to shift rest of 1000 elements at different positions which is a big performance hit.
Can anyone tell me,in this scenario which one should we go for.
 
Sheriff
Posts: 21136
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An ArrayList has very fast access to its elements, but is slower for adding and deleting elements; the farther from the end, the slower it is.

A LinkedList is very fast if you need to add or delete near the start / end a lot, but for adding, deleting and retrieving from the middle it is also quite slow (unless you are using a ListIterator).
This is because, to find an element of the LinkedList, it first has to traverse to that element. Fortunately, it will choose the shortest path (either from the start or from the end), but if you want to insert, delete or retrieve near the middle, it will have to traverse half of the list before it finally arrives at that point.

Now I mentioned the ListIterator. This interface has methods to add, remove or set elements to the current position. Since this position is cached, there is no need to traverse the list anymore.
 
Raj Kumar Bindal
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply.
So you mean to say that,first of all we will observe which scenario will be used often,i mean deletion/insertion from start/end or from middle.
If it is from middle go for ArrayList,else go from linkedlist.
 
Rob Spoor
Sheriff
Posts: 21136
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it's in the middle, you'd have to perform some stress tests to see which one performs better.

A LinkedList will have to look up the index, but then adding is real fast.
An ArrayList will have a real fast lookup, but then has to shift a lot of elements.

I really can't tell which one will be faster.
 
Raj Kumar Bindal
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!