大概要求如下:
public class ByteArrayCache {
private int mMaxBytes;
private List<byte[]> mBuffers = new ArrayList<>(64);
public ByteArrayCache(int capacity) {
mMaxBytes = capacity;
}
}
public byte[] obtainByte(int len) {
}
public void recycle(byte[]buff) {
}
1.实现obtainByte和recycle两个方法,可以自行新增变量,实现byte[]数组的复用,防止频繁的内存申请和gc释放造成内存抖动
2.仿照lru进行设计
我当时的答案:
public class ByteArrayCache {
private int mMaxBytes;
private List<byte[]> mBuffers = new ArrayList<>(64);
public ByteArrayCache(int capacity) {
mMaxBytes = capacity;
}
}
public synchronized byte[] obtainByte(int len) {
byte[] result = null;
result = query(len);
if (null != result) {
return result;
} else {
result = new byte[len];
return result;
}
}
public synchronized void recycle(byte[]buff) {
mBuffers.add(buff);
while (currentBytesLen() > mMaxBytes) {
mBuffers.remove(0);
}
}
private byte[] query(int len) {
byte[] result = null;
for (byte[] t : mBuffers) {
if (t.length == len) {
result = t;
break;
}
}
mBuffers.remove(result);
return result;
}
private int currentBytesLen() {
int result = 0;
for (byte[] t : mBuffers) {
result += t.length;
}
return result;
}
}