【问题标题】:Cache the last 50 event values and calculate maximum缓存最后 50 个事件值并计算最大值
【发布时间】:2016-11-29 01:28:49
【问题描述】:

我正在尝试为我的大学项目实施一个程序,我必须缓存最新的 50 个事件并计算从事件中检索到的字段的最大值。

我不确定需要使用什么数据结构来维护严格允许最后 50 个值并在第 51 个到达时删除第一个值的列表。

我们是否有一个已经为此提供支持的 Collections 类?

我过去有 LinkedHashMap 的 removeEldestEntry() 函数,但它不适合这里的要求。

【问题讨论】:

  • 堆栈不允许我控制我可以在数据结构中拥有的元素数量。我的数据结构应该严格包含最后 50 个条目
  • 只需在添加对象后检查“while(stack.size()>50){stack.pop();}。

标签: java core


【解决方案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);
    }
}

希望对您有所帮助,或者至少给您一个想法。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 2019-05-21
    • 2013-05-13
    相关资源
    最近更新 更多