PIbd-23_Polevoy_S.V._SelfPr.../SetArtilleriesGeneric.java

71 lines
1.5 KiB
Java
Raw Normal View History

2022-10-24 22:14:33 +04:00
public class SetArtilleriesGeneric<T> {
private final Object[] _places;
public int getCount() {
return _places.length;
}
public SetArtilleriesGeneric(int count) {
_places = new Object[count];
}
2022-10-24 22:22:51 +04:00
public int insert(T artillery) {
return insert(artillery, 0);
2022-10-24 22:14:33 +04:00
}
2022-10-24 22:22:51 +04:00
public int insert(T artillery, int position) {
2022-10-24 22:14:33 +04:00
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")
2022-10-24 22:22:51 +04:00
public T remove(int position) {
2022-10-24 22:14:33 +04:00
if (position < 0 || position >= getCount())
{
return null;
}
var result = _places[position];
_places[position] = null;
return (T) result;
}
@SuppressWarnings("unchecked")
2022-10-24 22:22:51 +04:00
public T get(int position) {
2022-10-24 22:14:33 +04:00
if (position < 0 || position >= getCount()) {
return null;
}
return (T) _places[position];
}
}