Sobes.tech
Junior — Middle

What is the difference between the properties count and capacity in collections or data structures?

sobes.tech AI

Answer from AI

In collections and data structures, the properties Count and Capacity have different meanings:

  • Count — the number of elements currently contained in the collection.
  • Capacity — the number of elements the collection can hold without needing to resize.

For example, in List<T> in C#:

List<int> numbers = new List<int>(10); // Capacity = 10
numbers.Add(1);
numbers.Add(2);

Console.WriteLine(numbers.Count);    // Outputs 2
Console.WriteLine(numbers.Capacity); // Outputs 10

If the number of elements exceeds Capacity, the collection will automatically increase its size, allocating more memory.

What is the difference between the properties count… - sobes.tech