PIbd-21_KozyrevSS_GasolineT.../SetGeneric.java

75 lines
2.0 KiB
Java

import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class SetGeneric <T extends Object>{
private final ArrayList<T> _places;
public int Count() {return _places.size();}
private final int _maxCount;
public SetGeneric(int count)
{
_maxCount = count;
_places = new ArrayList<>();
}
public int Insert(T tanker)
{
return Insert(tanker, 0);
}
public int Insert(T tanker, int position)
{
if (position < 0 || position >= _maxCount)
return -1;
_places.add(position, tanker);
return position;
}
public T Remove(int position)
{
if (position < 0 || position >= Count())
return null;
var returning = _places.get(position);
_places.remove(position);
return returning;
}
public T Get(int position)
{
if (position < 0 || position >= Count())
{
return null;
}
return _places.get(position);
}
public Iterable<T> GetTankers(final Integer maxTankers) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
private int count = 0;
@Override
public boolean hasNext() {
return currentIndex < _places.size() && (maxTankers == null || count < maxTankers);
}
@Override
public T next() {
if (hasNext()) {
count++;
return _places.get(currentIndex++);
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
}