简体   繁体   English

在JAVA中创建不固定大小的字节数据结构的最佳方法是什么

[英]What is the best way to create byte data structure not fixed size in JAVA

I need to create data structure, lets call it ByteCache, which containes some amount of bytes and it should support such methods: 我需要创建数据结构,让我们称之为ByteCache,它包含一些字节,它应该支持以下方法:

1) ByteCache.length() - returns amount of bytes stored in it 2) ByteCache.add(Byte[] bytes) - adds new bytes to the end of presently contained inside 3) ByteCache.get(int offset, int length) - returns byte list from offset to offset+length bytes 1)ByteCache.length()-返回存储在其中的字节数2)ByteCache.add(Byte [] bytes)-将新字节添加到当前包含在其中的末尾3)ByteCache.get(int offset,int length)-将字节列表从offset返回到offset + length个字节

It's supposed that there will be one thread writer (which adds bytes to cache) and another thread which reads some amounts of written bytes if there already present. 假定会有一个线程编写器(它将字节添加到高速缓存),而另一个线程将读取一些已写入的字节(如果已经存在)。

So what is the best way to do such things in java? 那么在Java中做这些事情的最好方法是什么? May be there is such data structure, or some library ready to use, which I don't know, though I've read about some but didn't get a clue. 也许有这样的数据结构,或者一些可以使用的库,我不知道,尽管我已经阅读了一些但没有任何线索。 I'm absolutely new to java, so please be patient. 我对Java绝对是新手,所以请耐心等待。

You can implement this with an ArrayList under the hood. 您可以在后台使用ArrayList来实现它。 ArrayList is an array that expands when more data is added than capacity permits. ArrayList是一个数组,当添加的数据超出容量许可时,该数组会扩展。

Your ByteCache might look like 您的ByteCache可能看起来像

public class ByteCache {

    ArrayList<Byte> backing = new ArrayList<Byte>();

    public ByteCache(){
    }

    public ByteCache(Byte[] bytes){
        add(bytes);
    }

    public void add(Byte[] bytes){
        for(Byte b : bytes){
            backing.add(b);
        }
    }

    public int length(){
        return backing.size();
    }

    public Byte[] get(int offset, int length){
        if(offset < 0 || length < 1){
            return null;
        }

        Byte[] toRet = new Byte[length];

        for(int i = offset; i < offset + length; i++){
            if(i == backing.size()){
                break;
            }
            toRet[i - offset] = backing.get(i);
        }
        return toRet;
    }
}

You would need to implement your own get() and add() methods, but for length() a call to ArrayList's correct method should be enough. 您将需要实现自己的get()和add()方法,但是对于length()来说,调用ArrayList的正确方法就足够了。

PS ArrayList doesn't exactly expand - a new array is created that is double the size and all items are copied over. PS ArrayList不能完全扩展-创建一个新数组,其大小是原来的两倍,并且所有项目都将被复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM