From 8fc2d24e7e3b37f5e548660c80c8247a71636960 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B5=D1=80=D0=B3=D0=B5=D0=B9=20=D0=9F=D0=BE=D0=BB?= =?UTF-8?q?=D0=B5=D0=B2=D0=BE=D0=B9?= Date: Sat, 5 Nov 2022 16:20:44 +0400 Subject: [PATCH] First stage: Array was replaced with ArrayList --- SetArtilleriesGeneric.java | 52 ++++++++++++++------------------------ 1 file changed, 19 insertions(+), 33 deletions(-) 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(); } }