diff --git a/SetArtilleriesGeneric.java b/SetArtilleriesGeneric.java index 77d1f52..be9ad0c 100644 --- a/SetArtilleriesGeneric.java +++ b/SetArtilleriesGeneric.java @@ -1,12 +1,18 @@ +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Objects; + public class SetArtilleriesGeneric { - private final Object[] _places; + private final ArrayList _places; + private final int _maxCount; public int getCount() { - return _places.length; + return _places.size(); } public SetArtilleriesGeneric(int count) { - _places = new Object[count]; + _maxCount = count; + _places = new ArrayList<>(count); } public int insert(T artillery) { @@ -14,57 +20,37 @@ public class SetArtilleriesGeneric { } public int insert(T artillery, int position) { - if (position < 0 || position >= getCount()) { + if (position < 0 || position >= getCount() || getCount() == _maxCount) { return -1; } - if (_places[position] == null) { - _places[position] = artillery; - return position; - } + _places.add(position, artillery); - int firstNull = -1; - - for (int i = position + 1; i < getCount(); i++) - { - if (_places[i] == null) - { - firstNull = i; - break; - } - } - - if (firstNull == -1) - { - return -1; - } - - System.arraycopy(_places, position, _places, position + 1, firstNull - position); - - _places[position] = artillery; return position; } - @SuppressWarnings("unchecked") public T remove(int position) { if (position < 0 || position >= getCount()) { return null; } - var result = _places[position]; + T result = _places.get(position); - _places[position] = null; + _places.remove(position); - return (T) result; + return result; } - @SuppressWarnings("unchecked") public T get(int position) { if (position < 0 || position >= getCount()) { return null; } - return (T) _places[position]; + return _places.get(position); + } + + public Iterator getArtilleries() { + return _places.stream().filter(Objects::nonNull).iterator(); } }