寻找一个循环固定大小基于数组的deque [英] Looking for a circular fixed size array-based deque

查看:178
本文介绍了寻找一个循环固定大小基于数组的deque的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一个 Deque ,它具有以下特征:

I'm looking for a Deque which has the following characteristics:


  • 它有固定大小

  • 如果我在head / tail元素添加元素在相对端删除

  • 它是基于数组的,所以我
  • 可以在固定时间访问随机元素
  • 我可以在前面或末尾添加元素(deque)

  • it has fixed size
  • if I add elements at the head/tail elements at the opposite end drop out
  • it is array-based so I can access random elements in constant time
  • I can add elements at the front or at the end (deque)

我检查了 JCF 中的 Deque 实现,但我没有找到合适的。

I checked the Deque implementations in the JCF but I did not find anything that fits.

推荐答案

因为我喜欢写自己的数据类型,

Because I love writing my own data types,

import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class Ring {

    private String[] data;
    int n = 0;

    public Ring(int size) {
        data = new String[size];
    }

    public void push(String s) {
        data[n] = s;
        n = (n + 1) % data.length;
    }

    public void shift(String s) {
        data[n = (n - 1) % data.length] = s;
    }

    public String get(int index) {
        return data[(n + index) % data.length];
    }

    public static class Examples {

        @Test
        public void shouldDropElementsWhenPushingTooFar() {
            Ring ring = new Ring(3);
            ring.push("A");
            ring.push("B");
            ring.push("C");
            ring.push("D");
            ring.push("E");
            assertEquals("C", ring.get(0));
            assertEquals("D", ring.get(1));
            assertEquals("E", ring.get(2));
        }

        @Test
        public void shouldAddElementsAtTheFront() {
            Ring ring = new Ring(3);
            ring.push("A");
            ring.push("B");
            ring.push("C");
            ring.push("D");
            ring.push("E");
            // rewind
            ring.shift("B");
            assertEquals("B", ring.get(0));
            assertEquals("C", ring.get(1));
            assertEquals("D", ring.get(2));
        }

    }

}

这篇关于寻找一个循环固定大小基于数组的deque的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆