Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace DelegatesAndEvents
- {
- public class CustomList<T>
- where T : IComparable<T>
- {
- private const int DefaultSize = 16;
- private const string Separator = ", ";
- private T[] elements;
- private int index;
- public CustomList()
- : this(DefaultSize)
- {
- }
- public CustomList(int initialSize)
- {
- this.elements = new T[initialSize];
- }
- public int Count
- {
- get
- {
- return this.index;
- }
- }
- public int Capacity
- {
- get
- {
- return this.elements.Length;
- }
- }
- private bool ResizeIsNeeded()
- {
- return this.elements.Length == this.index;
- }
- private void DoubleUpTheSizeOfTheArray()
- {
- int sizeOfNewArray = this.index * 2;
- T[] newArray = new T[sizeOfNewArray];
- for (int currentElement = 0; currentElement < this.elements.Length; currentElement++)
- {
- newArray[currentElement] = this.elements[currentElement];
- }
- this.elements = newArray;
- }
- private ElementSearchResult FindMatchingElement(T elementToRemove)
- {
- bool matchIsFound = false;
- int lastIndex;
- for (lastIndex = 0; lastIndex < this.index; lastIndex++)
- {
- T currentElement = this.elements[lastIndex];
- if (currentElement.CompareTo(elementToRemove) == 0)
- {
- matchIsFound = true;
- break;
- }
- }
- return new ElementSearchResult(lastIndex, matchIsFound);
- }
- private void RemoveElementAtIndex(int indexToRemove)
- {
- for (int moveIndex = indexToRemove; moveIndex < this.index - 1; moveIndex++)
- {
- this.elements[moveIndex] = this.elements[moveIndex + 1];
- }
- }
- public void Add(T elementToAdd)
- {
- if (this.ResizeIsNeeded())
- {
- this.DoubleUpTheSizeOfTheArray();
- }
- this.elements[this.index] = elementToAdd;
- this.index++;
- }
- public bool Remove(T elementToRemove)
- {
- ElementSearchResult searchResult = this.FindMatchingElement(elementToRemove);
- if (searchResult.MatchIsFound)
- {
- this.RemoveElementAtIndex(searchResult.LastIndex);
- this.index--;
- }
- return searchResult.MatchIsFound;
- }
- public override string ToString()
- {
- IEnumerable<T> elementsToShow = this.elements.Take(this.index);
- return string.Join(Separator, elementsToShow);
- }
- private class ElementSearchResult
- {
- public ElementSearchResult(int lastIndex, bool matchIsFound)
- {
- this.LastIndex = lastIndex;
- this.MatchIsFound = matchIsFound;
- }
- public int LastIndex { get; set; }
- public bool MatchIsFound { get; set; }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement