2016-11-29 45 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); 
    } 
} 

希望帮助,或者至少给你一个想法。 :)