I need to create data structure, lets call it ByteCache, which containes some amount of bytes and it should support such methods:
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
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? 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.
You can implement this with an ArrayList under the hood. ArrayList is an array that expands when more data is added than capacity permits.
Your ByteCache might look like
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.
P.S. ArrayList doesn't exactly expand - a new array is created that is double the size and all items are copied over.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments