using ProjectElectroTrans.Exceptions; using System.Collections.Generic; namespace ProjectElectroTrans.CollectionGenericObjects; /// /// Параметризованный набор объектов /// /// Параметр: ограничение - ссылочный тип public class MassiveGenericObjects : ICollectionGenericObjects where T : class { /// /// Массив объектов, которые храним /// private T?[] _collection; public int Count => _collection.Length; public int MaxCount { get { return _collection.Length; } set { if (value > 0) { if (_collection.Length > 0) { Array.Resize(ref _collection, value); } else { _collection = new T?[value]; } } } } public CollectionType GetCollectionType => CollectionType.Massive; /// /// Конструктор /// public MassiveGenericObjects() { _collection = Array.Empty(); } public T? Get(int position) { if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } public int Insert(T obj, IEqualityComparer? comparer = null) { if (comparer != null) { for (int i = 0; i < Count; i++) { if (comparer.Equals(_collection[i], obj)) { throw new CollectionInsertException(obj); } } } // вставка в свободное место набора for (int i = 0; i < Count; i++) { if (_collection[i] == null) { _collection[i] = obj; return i; } } throw new CollectionOverflowException(Count); } public int Insert(T obj, int position, IEqualityComparer? comparer = null) { // проверка позиции if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (comparer != null) { for (int i = 0; i < Count; i++) { if (comparer.Equals(_collection[i], obj)) { throw new CollectionInsertException(obj); } } } if (_collection[position] != null) { bool pushed = false; for (int index = position + 1; index < Count; index++) { if (_collection[index] == null) { position = index; pushed = true; break; } } if (!pushed) { for (int index = position - 1; index >= 0; index--) { if (_collection[index] == null) { position = index; pushed = true; break; } } } if (!pushed) { throw new CollectionOverflowException(Count); } } _collection[position] = obj; return position; } public T? Remove(int position) { // проверка позиции if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) throw new ObjectNotFoundException(position); T? temp = _collection[position]; _collection[position] = null; return temp; } public IEnumerable GetItems() { for (int i = 0; i < _collection.Length; ++i) { yield return _collection[i]; } } public void CollectionSort(IComparer comparer) { List lst = [.._collection]; lst.Sort(comparer.Compare); for (int i = 0; i < _collection.Length; ++i) { _collection[i] = lst[i]; } } }