Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- public class GenericList<T>
- {
- private T[] elements;
- private int count = 0;
- public GenericList(int capacity)
- {
- this.elements = new T[capacity];
- }
- public void Add(T element)
- {
- if (count >= elements.Length)
- {
- StretchCapacity();
- }
- elements[count] = element;
- count++;
- }
- private void StretchCapacity()
- {
- T[] tempArray = new T[elements.Length * 2];
- Array.Copy(elements, 0, tempArray, 0, elements.Length);
- elements = tempArray;
- }
- public void Delete(T point)
- {
- int index = Array.IndexOf(elements,point);
- //T[] tempArray = (T[])elements.Clone();
- //elements = new T[tempArray.Length];
- //for (int i = 0, j = 0; i < tempArray.Length; i++, j++)
- //{
- // if (i != index)
- // {
- // elements[j] = tempArray[i];
- // }
- // else
- // {
- // j--;
- // }
- //}
- T[] tempArray = (T[])elements.Clone();
- elements = new T[tempArray.Length];
- Array.Copy(tempArray, index + 1, elements, index, elements.Length - index - 1);
- count--;
- }
- public int FindByValue(T element)
- {
- int myIndex = Array.IndexOf(elements, element);
- return myIndex; //return index ot the element
- }
- public void InsertElement(int position, T element)
- {
- if (count == elements.Length)
- {
- StretchCapacity();
- }
- //T[] tempArray = (T[])elements.Clone();
- //elements = new T[tempArray.Length];
- //for (int i = 0, j = 0; i < tempArray.Length; i++, j++)
- //{
- // if (i != position)
- // {
- // elements[i] = tempArray[j];
- // }
- // else
- // {
- // elements[i] = element;
- // j--;
- // }
- //}
- Array.Copy(elements, position, elements, position + 1, elements.Length - position-1);
- elements[position] = element;
- count++;
- }
- public void Clear()
- {
- int length;
- length = elements.Length;
- elements = new T[length];
- }
- public override string ToString()
- {
- string concatenated = string.Join(",", elements.Select(x => x.ToString()).ToArray());
- return concatenated;
- }
- public T this[int index]
- {
- get
- {
- if (index >= count)
- {
- throw new IndexOutOfRangeException(String.Format(
- "Invalid index: {0}.", index));
- }
- T result = elements[index];
- return result;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement