你为什么不返回一个扩展List
并覆盖一些内部方法的类来欺骗其他类认为它只是一个子集。
例如,在您的子列表方法中,您可能会这样做......
public List<E> subList(int startPosition, int endPosition) {
return new SmallerList(this,startPosition,endPosition);
}
并创建一个SmallerList
像这样的类...
public class SmallerList extends List {
List parentList = null;
int startPosition = 0;
int endPosition = 0;
public SmallerList(List parentList, int startPosition, int endPosition){
this.parentList = parentList;
this.startPosition = startPosition;
this.endPosition = endPosition;
}
// overwrite some directly to appear smaller
public int size(){
return endPosition-startPosition;
}
// overwrite others to make adjustments to the correct position in the parentList
public void add(int index, Object object){
parentList.add(index+startPosition,object);
}
// overwrite others to only search between startPosition and endPosition
public boolean contains (Object object){
for (int i=startPosition;i<endPosition;i++){
if (parentList.get(i).equals(object)){
return true;
}
}
return false;
}
// etc. for all other methods of List.
}
使用这种方法,所有方法仍然作用于底层parentList
,但是任何对SmallerList
诸如add()
, get()
, contains()
, size()
, 的查询都被欺骗认为它们只在一个较小的List