スタックに50個以上の要素を持たずに制限を維持できると思います。サイズを最初に確認してから、新しいものを追加する前に最も古いエントリを削除するだけです。私は助け、または少なくともあなたのアイデアを与えることを願っています...
import java.util.Stack;
public class SO_40856348
{
public static void main(String[] args)
{
Stack<String> stack = new Stack<>();
// add 10 events to the stack (0-9)
for(int x = 0; x<10; x++)
{
String event = "Event-"+x;
System.out.println("At iteration [" + x + "] before adding event [" + event + "] stack contains:");
printStack(stack);
addEvent(stack, event);
System.out.println("At iteration [" + x + "] after adding event [" + event + "] stack contains:");
printStack(stack);
}
// dump events to console
System.out.println("At the end of the program the stack contains:");
printStack(stack);
}
public static void printStack(Stack<String> stack)
{
for(String e : stack)
{
System.out.println(e);
}
}
public static void addEvent(Stack<String> stack, String event)
{
/* Never more than 5 events in the stack, if we current have 5,
* remove one and immediately add the next one.
*/
if(stack.size() == 5)
{
// remove the oldest entry from the bottom of the stack
stack.remove(0);
}
// push the newest entry onto the top of the stack
stack.push(event);
}
}
効率や、問題の正確な性質はなく、思考についてはよく分かりません。 :)
あなたはおそらくhttps://www.tutorialspoint.com/java/util/stack_pop.htmを探しています –
スタックは私がデータ構造に持つことができる要素の数を制御することはできません。私のデータ構造は厳密に最後の50のエントリを含むべきです –
ちょうどあなたがあなたのオブジェクトを追加した直後に "while(stack.size()> 50){stack.pop();} –