Sobes.tech
Junior

What is the difference between a list and an array?

sobes.tech AI

Answer from AI

An array has a fixed size determined at creation and stores homogeneous elements in a contiguous block of memory. Access to elements by index is fast (O(1)).

A List<T> is a dynamic collection that can change its size. It also stores homogeneous elements but uses an internal array. When adding elements, if the internal array is full, a new, larger array is created and elements are copied. Index access is also fast (O(1)), but add/remove operations in the middle of the list can be slower (O(n)) due to shifting elements.

Main differences:

  • Size: Array — fixed, List — dynamic.
  • Add/remove performance: Array — size cannot be changed, List — can be slower in the middle.
  • Memory usage: List may allocate more memory than actually used to allow for dynamic growth.

Example of creation:

// Array
int[] array = new int[10]; // Size 10

// List
List<int> list = new List<int>(); // Initially empty
What is the difference between a list and an array… - sobes.tech