Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Defining_Classes_Part_2
- {
- public class GenericList<T> : ICountable, IGenericList<T>, IGenericList
- {
- private const int _defaultCapacity = 4;
- private T[] _elements;
- private int _count;
- private int _capacity;
- public GenericList()
- {
- this._elements = new T[_defaultCapacity];
- this._capacity = _defaultCapacity;
- }
- public GenericList(int capacity)
- {
- this._elements = new T[capacity];
- this._capacity = capacity;
- }
- public int Count
- {
- get
- {
- return this._count;
- }
- }
- public void Add(T element)
- {
- if (_count == _elements.Length)
- {
- Expand();
- }
- this._elements[this._count++] = element;
- }
- public T this[int index]
- {
- get
- {
- if (index >= _count)
- {
- throw new IndexOutOfRangeException();
- }
- return this._elements[index];
- }
- set
- {
- if (index >= _count)
- {
- throw new IndexOutOfRangeException();
- }
- this._elements[index] = value;
- }
- }
- public void RemoveAt(int index)
- {
- if (index >= _count)
- {
- throw new IndexOutOfRangeException();
- }
- for (int i = index; i < this._count -1; i++)
- {
- _elements[i] = _elements[i + 1];
- }
- _elements[this._count - 1] = default(T);
- _count--;
- }
- public override string ToString()
- {
- var result = new StringBuilder();
- for (var i = 0; i < this.Count; i++)
- {
- result.Append(this._elements[i]);
- if (i != this.Count - 1)
- {
- result.Append(", ");
- }
- }
- return result.ToString();
- }
- private void Expand()
- {
- var newElements = new T[2 * this._capacity];
- this._capacity *= 2;
- for (int i = 0; i < _count; i++)
- {
- newElements[i] = _elements[i];
- }
- this._elements = newElements;
- }
- public void Clear()
- {
- for (int i = 0; i < _count; i++)
- {
- this._elements[i] = default(T);
- }
- }
- public int Find(T element)
- {
- string searchFor = element.ToString();
- for (int i = 0; i < _count; i++)
- {
- if (this._elements[i].ToString() == searchFor)
- {
- return i;
- }
- }
- return -1;
- }
- public void InsertAt(T element, int index)
- {
- if (_count == _elements.Length)
- {
- Expand();
- }
- this.Add(this._elements[_elements.Length - 1]);
- for (int i = _count - 1; i > index; i--)
- {
- _elements[i] = _elements[i - 1];
- }
- _elements[index] = element;
- }
- }
- interface ICountable
- {
- int Count { get; }
- }
- interface IGenericList<T>
- {
- void Add(T element);
- void RemoveAt(int index);
- void Clear();
- void InsertAt(T element, int Index);
- }
- interface IGenericList
- {
- void RemoveAt(int index);
- void Clear();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement