Java.Collections.You need to add 1 million elements, what structure do you use?

When you need to add 1 million elements, the best choice depends on where and how you’re adding them.


🧪 Scenario: Adding 1 million elements to the end

Use ArrayList

Why?

  • Appending to the end is O(1) amortized.
  • Resizing happens occasionally, but it’s fast overall.
  • Excellent cache performance due to contiguous memory.
  • Much faster iteration and access than LinkedList.
List<Integer> list = new ArrayList<>(1_000_000); // Pre-size to avoid resizing
for (int i = 0; i < 1_000_000; i++) {
    list.add(i);
}

This is the most efficient way—fast and memory-friendly.

🧪 Scenario: Adding 1 million elements to the beginning

ArrayList is a poor choice here — every insertion shifts all existing elements → O(n²) total time.

Use LinkedList if you must insert at the beginning:

List<Integer> list = new LinkedList<>();
for (int i = 0; i < 1_000_000; i++) {
    list.add(0, i); // Fast in LinkedList, terrible in ArrayList
}

But note: iterating through a LinkedList of a million elements is slower and uses more memory.

🧠 Bonus Pro Tip:

If you’re doing lots of insertions at both ends and performance matters, consider:

  • Deque (ArrayDeque or LinkedList) — optimized for head & tail operations.
  • ArrayList with batch add at the end.

🔚 Summary:

TaskBest Structure
Add 1M to the endArrayList
Add 1M to the beginningLinkedList
Add 1M randomly in middle❌ Neither great — consider data structure rethink (e.g., TreeList, Deque)
This entry was posted in Без рубрики. Bookmark the permalink.