PIbd-21_Valitov_D.F_Sailboa.../Sailboat/SetBoatsGeneric.cs
2023-04-22 01:09:06 +04:00

101 lines
2.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat
{
class SetBoatsGeneric<T> where T : class, IEquatable<T>
{
private readonly List<T> _places;
public int Count => _places.Count;
private readonly int _maxCount;
private int BusyPlaces = 0;
public SetBoatsGeneric(int count)
{
_maxCount = count;
_places = new List<T>();
}
public int Insert(T boat)
{
return Insert(boat, 0);
}
public int Insert(T boat, int position)
{
if (_places.Contains(boat))
{
return -1;
}
if (Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position >= _maxCount || BusyPlaces == _maxCount)
{
return -1;
}
BusyPlaces++;
_places.Insert(position, boat);
return position;
}
public T Remove(int position)
{
if (position >= Count || position < 0)
{
throw new BoatNotFoundException(position);
}
if (position < 0 || position >= _maxCount)
{
return null;
}
BusyPlaces--;
T boat = _places[position];
_places.RemoveAt(position);
return boat;
}
public T this[int position]
{
get
{
if (position < 0 || position >= _maxCount) return null;
return _places[position];
}
set
{
Insert(value, position);
}
}
public IEnumerable<T> GetBoats()
{
foreach (var boat in _places)
{
if (boat != null)
{
yield return boat;
}
else
{
yield break;
}
}
}
public void SortSet(IComparer<T> comparer)
{
if (comparer == null)
{
return;
}
_places.Sort(comparer);
}
}
}