2016-11-29 44 views
-3

我正在嘗試爲我的大學項目實現一個程序,我必須緩存最新的50個事件並計算從事件中檢索到的字段的最大值。緩存最近的50個事件值並計算最大值

我不能確定爲需要被用來維持列表,它嚴格允許最後50個值,並刪除第一個在第51到達什麼樣的數據結構。

我們有一個Collections類,它已經爲此提供了支持嗎?

我在過去有LinkedHashMap的removeEldestEntry()函數,但它不適合這裏的要求。

+0

你可能尋找https://www.tutorialspoint.com/java/util/stack_pop.htm –

+0

堆棧不會讓我控制,我可以在數據結構元素的數量。我的數據結構應嚴格包含在過去的50項 –

+0

只是做檢查「,而(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); 
    } 
} 

希望幫助,或者至少給你一個想法。 :)