2016-11-29 6 views
-3

大学プロジェクト用のプログラムを実装しようとしています。最新の50個のイベントをキャッシュし、イベントから取得したフィールドの最大値を計算する必要があります。最後の50個のイベント値をキャッシュして最大値を計算する

最後の50個の値を厳密に許容するリストを維持するために使用する必要があるデータ構造が不明で、51番目が到着したときに最初のデータ構造を削除します。

既にこれをサポートしているCollectionsクラスがありますか?

私は過去にLinkedHashMapのremoveEldestEntry()関数を持っていましたが、ここでの要件には合いません。

+0

あなたはおそらくhttps://www.tutorialspoint.com/java/util/stack_pop.htmを探しています –

+0

スタックは私がデータ構造に持つことができる要素の数を制御することはできません。私のデータ構造は厳密に最後の50のエントリを含むべきです –

+0

ちょうどあなたがあなたのオブジェクトを追加した直後に "while(stack.size()> 50){stack.pop();} –

答えて

1

スタックに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); 
    } 
} 

効率や、問題の正確な性質はなく、思考についてはよく分かりません。 :)

関連する問題