圆列表,迭代直到结束或中断,记住迭代

时间:2015-07-28 14:27:36

标签: java dictionary iteration

这是一个如何使用的简化示例!

包含n个元素的地图(在此示例中有三个; OneTwoThree)。映射定义为<String, DecrementableInteger>,后者是可变整数的包装器。

class DecrementableInteger
{
    private int timeLeftMax;
    private int timeLeft;

    public DecrementableInteger (int v) {
        timeLeft = v;
        timeLeftMax = v;
    }

    public void update (int v) {
        timeLeft -= v;
    }

    public int get () {
        return timeLeft;
    }

    public void reset () {
        timeLeft = timeLeftMax;
    }
}

然后有它的用法。

class Test
{
    private final Map<String, DecrementableInteger> integers = new CircleHashMap<>(); //?
    private String activeKey = null;

    Test () {
        integers.put("One", new DecrementableInteger(4));
        integers.put("Two", new DecrementableInteger(1));
        integers.put("Three", new DecrementableInteger(2));
    }

    void update () {
        if (activeKey == null) {
            for (Entry<String, DecrementableInteger> e : integers.entrySet()) {
                e.getValue().update (1);
                if (e.getValue().get () <= 0) {
                    System.out.println(e.getKey() + " just finished, resetting.");
                    e.getValue().reset();
                    activeKey = e.getKey();
                    break;
                }
            }
        } else {
            System.out.println(activeKey + " did their thing, continuing!");
            activeKey = null;
        }
    }
}

每秒多次调用update方法。

第一次迭代将给出以下结果。

  1. One =&gt; 3
  2. 两个=&gt; 0,Two just finished, resetting.两个=&gt; 1
  3. 迭代中断,下次继续Three

    1. 三=&gt; 1
    2. 迭代完成,下次重新开始One

      1. One =&gt; 2,
      2. 两个=&gt; 0,Two just finished, resetting.两个=&gt; 1
      3. 迭代中断,下次继续Three

        1. 三=&gt; 0,Three just finished, resetting.三=&gt; 2
        2. 迭代完成,下次重新开始One

          1. One =&gt; 1
          2. ...
          3. 代码需要具备以下特性:

            • 地图需要记住它的顺序,它不能随意乱扔它们。
            • 代码需要记住它是否已经停止;目前位于activeKey
            • 迭代需要能够从activeKey
            • 开始

            CircleList是否有效且有效的解决方案?如果是这样,该解决方案将是什么样的。

1 个答案:

答案 0 :(得分:1)

您是否需要使用地图,或者您可以使用列表吗?

如果需要是Map,则应使用TreeMap,因为TreeMap已定义了排序。然后你需要创建一个特殊的迭代器,它基本上遍历树,并在到达结束时返回到元素1。