All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.fathzer.games.util.Stack Maven / Gradle / Ivy

The newest version!
package com.fathzer.games.util;

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

/** A class that manages a stack of objects.
 * 
This class stores and retrieves data stored in a list, manages the current list index, and automatically creates data instance when if needed. * @param The class of data containers. */ public class Stack { private final Supplier builder; private final List backups; private int index; private T current; /** Constructor. *
Creates a stack with an element * @param builder A supplier that can create a data container. */ public Stack(Supplier builder) { this.builder = builder; this.backups = new ArrayList<>(); this.index = 0; this.current = null; } /** Gets the current element. * @return an element */ public T get() { if (current==null) { if (index>=backups.size()) { current = builder.get(); backups.add(current); } else { current = backups.get(index); } } return current; } /** Sets the current element. * @param element The element to set */ public void set(T element) { current = element; if (index>=backups.size()) { backups.add(current); } else { backups.set(index, current); } } /** Moves to the next element. *
Creates the element if needed. */ public void next() { index++; current = null; } /** Moves to previous element. * @throws NoSuchElementException if current element is the first one */ public void previous() { if (index==0) { throw new NoSuchElementException(); } index--; current = backups.get(index); } /** Clears the stack. */ public void clear() { this.backups.clear(); this.index = 0; this.current = null; } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy