1.MaxSizeArrayList
import androidx.annotation.NonNull;
import java.util.ArrayList;
import java.util.Collection;
public class MaxSizeArrayList extends ArrayList {
private final long mMaxSize;
public MaxSizeArrayList(int maxSize) {
this.mMaxSize = maxSize;
}
@Override
public synchronized boolean add(Object o) {
if (size() == mMaxSize) {//大于最大长度时,移除第一个
remove(0);
}
return super.add(o);
}
@Override
public synchronized Object remove(int index) {
return super.remove(index);
}
@Override
public synchronized boolean addAll(@NonNull Collection c) {
Object[] objects = c.toArray();
for (Object o : objects) {
add(o);
}
return size() == mMaxSize;
}
@Deprecated
@Override
public synchronized void add(int index, Object element) {
//可自定义逻辑
}
@Deprecated
@Override
public synchronized boolean addAll(int index, @NonNull Collection c) {
//可自定义逻辑
return false;
}
}
2.MaxSizeLinkedList
import androidx.annotation.NonNull;
import java.util.Collection;
import java.util.LinkedList;
public class MaxSizeLinkedList extends LinkedList {
private final long mMaxSize;
public MaxSizeLinkedList(long mMaxSize) {
this.mMaxSize = mMaxSize;
}
@Override
public synchronized boolean add(Object o) {
if(size()==mMaxSize){//大于最大长度时,移除第一个
removeFirst();
}
return super.add(o);
}
@Override
public synchronized Object removeFirst() {
return super.removeFirst();
}
@Override
public synchronized boolean addAll(@NonNull Collection c) {
Object[] objects = c.toArray();
for (Object o : objects) {
add(o);
}
return size() == mMaxSize;
}
@Deprecated
@Override
public synchronized void add(int index, Object element) {
//可自定义逻辑
}
@Deprecated
@Override
public synchronized boolean addAll(int index, @NonNull Collection c) {
//可自定义逻辑
return false;
}
}