How to implement the method Remove(T item) for your collection (the same as in List<> ), which removes the specified element, but does not change the actual capacity of the array?

I have a collection and its parameters:

 T[] arreay = new T[5]; public int count; public int size; public void Insert(int index, T item) { size++; T[] arr = new T[size]; for (int i = 0; i < index; ++i) { arreay[i] = arr[i]; } arreay[index] = item; for (int i = index + 1; i < size; ++i) { arreay[i] = arr[i]; } } 
  • Comments are not intended for extended discussion; conversation moved to chat . - Yuriy SPb

1 answer 1

Simple implementation of an array-based list:

  1. Store the array of elements itself ( elemenets )
  2. Store the actual number of elements in the array ( size ). This will allow not re-creating the array when calling the Remove method, as well as initially having an array of non-zero size and increasing the array size "with a margin" (for simplicity in the example code, the array is increased only to the required size)

Insert(int index, T item) method Insert(int index, T item) :

  1. Checks that index valid
  2. Checks that the array will include another element ( size + 1 ) and, if necessary, increase the size of the array
  3. Shifts elements in an array from index to size to the right by one position ( index -> index + 1 , ..., size - 1 -> size )
  4. Adds a new item at index index
  5. Increases size by one.

Remove(T item) method:

  1. Searches for the first occurrence of item in an array
  2. If the item is found (its index greater than or equal to 0), then:
    • Shifts elements from index to size left by one position ( index <- index + 1 , ..., size - 1 <- size )
    • Decreases size by one.

The Add(T item) method Add(T item) there was no discussion about it, but it is short and still had to be written to test the code):

  1. Checks that the array will include another element ( size + 1 ) and, if necessary, increase the size of the array
  2. Adds a new element to the end of the array (at the size index)
  3. Increases size by one.

Code example:

 public class MyList<T> { private T[] elements = new T[5]; private int size = 0; public void Insert(int index, T item) { if (index < 0 || index >= size) throw new IndexOutOfRangeException($"Index: {index}, Size: {size}"); EnsureCapacity(size + 1); for (var i = size; i > index; i--) elements[i] = elements[i - 1]; elements[index] = item; size++; } public void Remove(T item) { var index = Array.IndexOf(elements, item, 0, size); if (index < 0) return; for (var i = index; i < size - 1; i++) elements[i] = elements[i + 1]; size--; } public void Add(T item) { EnsureCapacity(size + 1); elements[size] = item; size++; } private void EnsureCapacity(int capacity) { if (elements.Length < capacity) { var arr = new T[capacity]; Array.Copy(elements, arr, size); elements = arr; } } }