Pibd-23_Zhelovanov_D.Y._Bat.../SetBattleshipGeneric.java

60 lines
1.4 KiB
Java
Raw Normal View History

2022-12-20 21:50:09 +04:00
public class SetBattleshipGeneric <T>
{
private final T[] _places;
public SetBattleshipGeneric(int count) {
_places = (T[]) new Object[count];
}
public int Count() {
return _places.length;
}
public int Insert(T battleship)
{
return Insert(battleship, 0);
}
public int Insert(T battleship, int position)
{
if (position >= _places.length || position < 0) return -1;
if (_places[position] == null) {
_places[position] = battleship;
return position;
}
int emptyEl = -1;
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] = battleship;
return position;
}
public T Remove (int position) {
if (position >= _places.length || position < 0) return null;
T result = _places[position];
_places[position] = null;
return result;
}
public T Get(int position)
{
if (position >= Count() || position < 0)
{
return null;
}
return _places[position];
}
}