I am experienced in other languages but very new to Java. As an optimisation for a specific situation, I'm trying to implement an iterable container class from an array, as I know my container will hold a maximum of 4 items at a time, and those items each belong in a specific index, not first in gets the lowest index available.
To save me checking for null when I iterate over the list, I only want the non-null values returned for iteration... Would the below override of 'iterator()' work? And is there any chance the garbage collector going to clear up the iterable list I return before I get to iterate over it? Or is there a better way to achieve this maybe?
class FixedArray<T> implements Iterable<T> {
FixedArray() {}
public void add(byte index, T item) {
array[index] = item;
}
@Override
public Iterator<T> iterator() {
List<T> listWithoutNull = new ArrayList<>();
for (Item item: array) {
if (item != null) {
listWithoutNull.add(item);
}
}
return listWithoutNull.iterator();
}
private final T[] array = { null, null, null, null };
}