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

57 lines
1.2 KiB
Java
Raw Normal View History

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Objects;
2022-10-24 22:14:33 +04:00
public class SetArtilleriesGeneric<T> {
private final ArrayList<T> _places;
private final int _maxCount;
2022-10-24 22:14:33 +04:00
public int getCount() {
return _places.size();
2022-10-24 22:14:33 +04:00
}
public SetArtilleriesGeneric(int count) {
_maxCount = count;
_places = new ArrayList<>(count);
2022-10-24 22:14:33 +04:00
}
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) {
if (position < 0 || position >= getCount() || getCount() == _maxCount) {
2022-10-24 22:14:33 +04:00
return -1;
}
_places.add(position, artillery);
2022-10-24 22:14:33 +04:00
return position;
}
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;
}
T result = _places.get(position);
2022-10-24 22:14:33 +04:00
_places.remove(position);
2022-10-24 22:14:33 +04:00
return result;
2022-10-24 22:14:33 +04:00
}
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 _places.get(position);
}
public Iterator<T> getArtilleries() {
return _places.stream().filter(Objects::nonNull).iterator();
2022-10-24 22:14:33 +04:00
}
}