PIbd-14_Pruidze_I.K_Simple_.../ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs
2024-06-15 09:05:36 +04:00

95 lines
2.0 KiB
C#

namespace ProjectCruiser.CollectionGenericObj;
public class ArrayGenObj<T> : ICollectionGenObj<T>
where T : class
{
// Массив объектов, которые храним
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount
{
set
{
if (value > 0)
{
if (_collection.Length > 0) Array.Resize(ref _collection, value);
else _collection = new T?[value];
}
}
}
// public int SetMaxCount { set { if (value > 0) { _collection = new T?[value]; } } }
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)
{
// any empty place
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = item;
return i;
}
}
return -1;
}
public int Insert(T? item, int index)
{
if (_collection[index] == null)
{
_collection[index] = item;
return index;
}
else
{
int min_diff = 100, min_index = 100;
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null
&& min_diff > Math.Abs(index - i))
{
min_diff = Math.Abs(index - i);
min_index = i;
}
}
_collection[min_index] = item;
return min_index;
}
return -1;
}
public T? Remove(int index)
{
T? item;
if (index < Count && index >= 0)
{
item = _collection[index];
_collection[index] = null;
return item;
}
return null;
}
}