aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/makamys/neodymium/util/RecyclingList.java
blob: ea240bb10cc1afade57722f3317547b0a93f2f72 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package makamys.neodymium.util;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

public class RecyclingList<T> {
    
    private Supplier<T> constructor;
    
    int nextIndex;
    private List<T> list;
    
    public RecyclingList(Supplier<T> constructor) {
        this.constructor = constructor;
        this.list = new ArrayList<T>();
    }
    
    public T get(int i) {
        while(list.size() <= i) {
            list.add(constructor.get());
        }
        return list.get(i);
    }
    
    public T next() {
        return get(nextIndex++);
    }
    
    public void reset() {
        nextIndex = 0;
    }

    public List<T> getAsList() {
        return list.subList(0, nextIndex);
    }
}