diff --git a/SelfPropelledArtilleryUnit/SetArtilleriesGeneric.cs b/SelfPropelledArtilleryUnit/SetArtilleriesGeneric.cs index 35c69f5..1ef147d 100644 --- a/SelfPropelledArtilleryUnit/SetArtilleriesGeneric.cs +++ b/SelfPropelledArtilleryUnit/SetArtilleriesGeneric.cs @@ -9,12 +9,14 @@ namespace Artilleries internal class SetArtilleriesGeneric where T : class { - private readonly T[] _places; - public int Count => _places.Length; + private readonly List _places; + public int Count => _places.Count; + private readonly int _maxCount; public SetArtilleriesGeneric(int count) { - _places = new T[count]; + _maxCount = count; + _places = new List(); } public int Insert(T artillery) @@ -24,39 +26,13 @@ namespace Artilleries public int Insert(T artillery, int position) { - if (position < 0 || position >= Count) + if (position < 0 || position >= Count || Count == _maxCount) { return -1; } - if (_places[position] == null) - { - _places[position] = artillery; - return position; - } + _places.Insert(position, artillery); - int firstNull = -1; - - for (int i = position + 1; i < Count; i++) - { - if (_places[i] == null) - { - firstNull = i; - break; - } - } - - if (firstNull == -1) - { - return -1; - } - - for (int i = firstNull; i > position; i--) - { - _places[i] = _places[i - 1]; - } - - _places[position] = artillery; return position; } @@ -69,18 +45,43 @@ namespace Artilleries var result = _places[position]; - _places[position] = null; + _places.RemoveAt(position); return result; } - public T Get(int position) + public T this[int position] { - if (position < 0 || position >= Count) + get { - return null; - } + if (position < 0 || position >= Count) + { + return null; + } - return _places[position]; + return _places[position]; + } + set + { + if (position >= 0 && position < Count) + { + Insert(value, position); + } + } + } + + public IEnumerable GetArtilleries() + { + foreach (var artillery in _places) + { + if (artillery != null) + { + yield return artillery; + } + else + { + yield break; + } + } } } }