First stage: Array was replaced with ArrayList
This commit is contained in:
parent
385eedd0b9
commit
8fc2d24e7e
@ -1,12 +1,18 @@
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.Objects;
|
||||
|
||||
public class SetArtilleriesGeneric<T> {
|
||||
private final Object[] _places;
|
||||
private final ArrayList<T> _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<T> {
|
||||
}
|
||||
|
||||
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<T> getArtilleries() {
|
||||
return _places.stream().filter(Objects::nonNull).iterator();
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user