Simple implementation of an array-based list:
- Store the array of elements itself (
elemenets ) - 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) :
- Checks that
index valid - Checks that the array will include another element (
size + 1 ) and, if necessary, increase the size of the array - Shifts elements in an array from
index to size to the right by one position ( index -> index + 1 , ..., size - 1 -> size ) - Adds a new item at index
index - Increases
size by one.
Remove(T item) method:
- Searches for the first occurrence of
item in an array - 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):
- Checks that the array will include another element (
size + 1 ) and, if necessary, increase the size of the array - Adds a new element to the end of the array (at the
size index) - 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; } } }