From 675c220c79a51c27319abca4c04eb67725850c2f 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: Mon, 24 Oct 2022 22:14:33 +0400 Subject: [PATCH] Added SetArtilleriesGeneric --- SetArtilleriesGeneric.java | 70 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 SetArtilleriesGeneric.java diff --git a/SetArtilleriesGeneric.java b/SetArtilleriesGeneric.java new file mode 100644 index 0000000..03d19a7 --- /dev/null +++ b/SetArtilleriesGeneric.java @@ -0,0 +1,70 @@ +public class SetArtilleriesGeneric { + private final Object[] _places; + + public int getCount() { + return _places.length; + } + + public SetArtilleriesGeneric(int count) { + _places = new Object[count]; + } + + public int Insert(T artillery) { + return Insert(artillery, 0); + } + + public int Insert(T artillery, int position) { + if (position < 0 || position >= getCount()) { + return -1; + } + + if (_places[position] == null) { + _places[position] = artillery; + return position; + } + + 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]; + + _places[position] = null; + + return (T) result; + } + + @SuppressWarnings("unchecked") + public T Get(int position) { + if (position < 0 || position >= getCount()) { + return null; + } + + return (T) _places[position]; + } +}