using ProjectCruiser.DrawningSamples; using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObj; public class ArrayGenObj : ICollectionGenObj where T : class { // Массив объектов, которые храним private T?[] _collection; // Максимально допустимое число объектов в массиве private int _maxCount; public int Count => _collection.Count(s => (s != null)); public int MaxCount { get { return _maxCount; } set { if (value > 0) { _maxCount = value; if (_collection.Length == 0) _collection = new T?[value]; else Array.Resize(ref _collection, value); } } } public CollectionType GetCollectionType => CollectionType.Array; public ArrayGenObj() { _collection = Array.Empty(); } // methods : public T? GetItem(int index) { if (index > _maxCount) throw new CollectionOverflowException(index); if (index < 0) throw new PositionOutOfCollectionException(index); if (_collection[index] == null) throw new ObjectNotFoundException(index); return _collection[index]; } public int Insert(T? item, IEqualityComparer? cmpr = null) { if (item == null) throw new NullReferenceException("> Inserting item is null"); else { if (cmpr != null && item == cmpr) { throw new Exception(); } } // выход за границы, курируется CollectionOverflowException if (Count >= _maxCount) throw new CollectionOverflowException(Count); // any empty place -> fill immediately for (int i = Count; i < _maxCount; i++) { if (_collection[i] == null) { _collection[i] = item; return i; } } return Count; } public int Insert(T? item, int index, IEqualityComparer? cmpr = null) { if (index < 0 || index >= _maxCount) throw new PositionOutOfCollectionException(index); if (Count >= _maxCount) throw new CollectionOverflowException(Count); if (item == null) throw new NullReferenceException("> Inserting item (at position) is null"); else { if (cmpr != null && item == cmpr) { throw new Exception(); } } if (_collection[index] == null) { _collection[index] = item; return index; } else { int min_diff = 100, firstNullIndex = 100; for (int i = 0; i < Count; i++) { if (_collection[i] == null && min_diff > Math.Abs(index - i)) { min_diff = Math.Abs(index - i); firstNullIndex = i; } } _collection[firstNullIndex] = item; return firstNullIndex; } } public T? Remove(int index) { if (index >= _maxCount || index < 0) // on the other positions items don't exist { throw new PositionOutOfCollectionException(index); } T? item = _collection[index]; _collection[index] = null; if (item == null) throw new ObjectNotFoundException(index); return item; } public IEnumerable GetItems() { for (int i = 0; i < MaxCount; ++i) { yield return _collection[i]; } } public void CollectionSort(IComparer comparer) { Array.Sort(_collection, comparer); } }