0

I was going through ArrayList internal implementation in Java and I found that ArrayList is dynamically increasing array and when the size gets increased , a new space is allocated and the previous records are moved there.So, when a large list is to be filled and the capacity is not known it is not recomended to use ArrayList.

The replacement that came to my mind was LinkedList.Going through LinkedList implementation but I have two consern

  1. When a for each loop is been executed does it means that everytime a node is been accessed it will traverse all the previous node .That will make worst case as o(n^2).

  2. If an iterator is used in the place of foreach wil it contribute anything to the performance or how does it differ from foreach.

Thank you for your reply in advance..

Soumik Dutta
  • 138
  • 2
  • 13
  • 2
    FYI: In general, growing an iterating over an `ArrayList` is faster (because it favors locality of reference) and uses less memory than a `LinkedList` (because it doesn't have to create an extra node object for each element in the collection), so your initial assumption is wrong. – Óscar López Dec 17 '16 at 15:04
  • 1
    The foreach loop uses an iterator, so it's O(1). Nonetheless, `LinkedList` is nearly always a bad choice, don't even think about using it before you wite a benchmark. And don't benchmark without using JMH (benchmarking in Java is very tricky). – maaartinus Dec 17 '16 at 15:10
  • This is my observation of inserting records in both ArrayList and LinkedList `-- 1000000 Total time needed ArrayList Insertion: 433 Total time needed LinkedList Insertion : 115 -- 10000000 Total time needed ArrayList Insertion: 4062 Total time needed LinkedList Insertion : 3971 -- 20000000 Total time needed ArrayList Insertion: 6814 Total time needed LinkedList Insertion : 9724` – Soumik Dutta Jan 06 '17 at 07:23

0 Answers0