118 lines
2.6 KiB
C#
118 lines
2.6 KiB
C#
|
|
namespace ProjectCruiser.CollectionGenericObj;
|
|
|
|
public class ArrayGenObj<T> : ICollectionGenObj<T>
|
|
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)
|
|
{
|
|
if (_collection.Length == 0) _collection = new T?[value];
|
|
else Array.Resize(ref _collection, value);
|
|
|
|
_maxCount = value;
|
|
}
|
|
}
|
|
}
|
|
|
|
public CollectionType GetCollectionType => CollectionType.Array;
|
|
|
|
public ArrayGenObj()
|
|
{
|
|
_collection = Array.Empty<T?>();
|
|
}
|
|
|
|
// methods :
|
|
public T? GetItem(int index)
|
|
{
|
|
if (index > Count || index < 0)
|
|
{
|
|
return null;
|
|
}
|
|
return _collection[index];
|
|
}
|
|
|
|
public int Insert(T? item)
|
|
{
|
|
if (Count >= _maxCount || item == null)
|
|
{
|
|
return -1;
|
|
}
|
|
|
|
// any empty place -> fill immediately
|
|
for (int i = 0; i < _collection.Length; i++)
|
|
{
|
|
if (_collection[i] == null)
|
|
{
|
|
_collection[i] = item;
|
|
return i;
|
|
}
|
|
}
|
|
return Count;
|
|
}
|
|
|
|
public int Insert(T? item, int index)
|
|
{
|
|
if (index >= _maxCount || Count >= _maxCount ||
|
|
index < 0 || _collection[index] != null
|
|
|| item == null)
|
|
{
|
|
return -1;
|
|
}
|
|
|
|
if (_collection[index] == null)
|
|
{
|
|
_collection[index] = item;
|
|
return index;
|
|
}
|
|
|
|
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 >= Count || index < 0)
|
|
// on the other positions items don't exist
|
|
{
|
|
return null;
|
|
}
|
|
|
|
T? item = _collection[index];
|
|
_collection[index] = null;
|
|
return item;
|
|
}
|
|
|
|
public IEnumerable<T?> GetItems()
|
|
{
|
|
for (int i = 0; i < MaxCount; ++i)
|
|
{
|
|
yield return _collection[i];
|
|
}
|
|
}
|
|
}
|
|
|