105 lines
2.2 KiB
C#
105 lines
2.2 KiB
C#
|
|
namespace ProjectCruiser.CollectionGenericObj;
|
|
|
|
public class ArrayGenObj<T> : ICollectionGenObj<T>
|
|
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.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)
|
|
{
|
|
// 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;
|
|
}
|
|
|
|
public IEnumerable<T?> GetItems()
|
|
{
|
|
for (int i = 0; i < _collection.Length; ++i)
|
|
{
|
|
yield return _collection[i];
|
|
}
|
|
}
|
|
}
|
|
|