I want to create a Stack in Java, but fix the size. For example, create a new Stack, set the size to 10, then as I push items to the stack it fills up and when it fills up t
You can use LinkedHashMap and override its removeEldestEntry method:
public class FixedStack extends LinkedHashMap {
private final int capacity;
public FixedStack(int capacity) {
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(final Map.Entry eldest) {
return super.size() > capacity;
}
}
And to test it:
public static void main(String[] args) {
FixedStack stack = new FixedStack(10);
long added = 0;
for (Locale locale : Locale.getAvailableLocales()) {
if (locale.getDisplayCountry().length() > 0) {
stack.put(added, locale.getDisplayCountry());
System.out.println(locale.getDisplayCountry());
added++;
}
}
System.out.println(String.format(">>>>>>>>> %s added",
added));
Iterator> iterator = stack.entrySet().iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next().getValue());
}
}
You just have to decide what you want to use as the key, I used a simple counter in the example.