diff --git a/Warship/Warship/SetWarshipsGeneric.cs b/Warship/Warship/SetWarshipsGeneric.cs index e119426..141ba87 100644 --- a/Warship/Warship/SetWarshipsGeneric.cs +++ b/Warship/Warship/SetWarshipsGeneric.cs @@ -9,69 +9,73 @@ namespace Warship internal class SetWarshipsGeneric where T : class { - private readonly T[] _places; + private readonly List _places; - public int Count => _places.Length; + public int Count => _places.Count; + + private readonly int _maxCount; public SetWarshipsGeneric(int count) { - _places = new T[count]; + _maxCount = count; + _places = new List(); } public int Insert(T warship) { - return Insert(warship, 0); + if (_places.Count + 1 >= _maxCount) + return -1; + _places.Insert(0, warship); + return 0; } public int Insert(T warship, int position) { - int EmptyEl = -1; - - if (position >= Count || position < 0) + if (position >= _maxCount || position < 0) return -1; - - if (_places[position] == null) - { - _places[position] = warship; - return 1; - } - - else if (_places[position] != null) - { - for (int i = position + 1; i < Count; i++) - if (_places[i] == null) - { - EmptyEl = i; - break; - } - - if (EmptyEl == -1) - return -1; - - for (int i = EmptyEl; i > position; i--) - _places[i] = _places[i - 1]; - } - - _places[position] = warship; - return 1; + if (_places.Count + 1 >= _maxCount) + return -1; + _places.Insert(position, warship); + return position; } public T Remove(int position) { - if (position >= Count || position < 0 || _places[position] == null) + if (position >= _maxCount || position < 0) return null; T deleted = _places[position]; - _places[position] = null; + _places.RemoveAt(position); return deleted; } - public T Get(int position) + public T this[int position] { - if (position >= Count || position < 0) - return null; - - return _places[position]; + get + { + if (position < 0 || position >= _maxCount) + return null; + return _places[position]; + } + set + { + if (position < 0 || position >= _maxCount) + Insert(value, position); + } + } + public IEnumerable GetWarships() + { + foreach (var warship in _places) + { + if (warship != null) + { + yield return warship; + } + else + { + yield break; + } + } } } }