我正在实现我自己的 LinkedList 类。
对于 sublist(int a,int b function) 方法,mycode 无法正常工作。如果进行任何更改,它应该在该方法之后根据(a 和 b 索引)(我成功)返回列表的子列表在子列表上,列表也必须生效(不成功)。例如,如果我执行
(list.sublist(1,4)).clear
:列表元素从 1 到 4 也应该清除。
我的代码是:
public List<E> subList(int arg0, int arg1) {
ArrayList<E> ar = new ArrayList<E>();
ListIterator myiter=listIterator(arg0);
int k = arg1 - arg0 + 1;
int i;
for(i = 0; i < k; ++i) {
ar.add((E) myiter.next());
}
List <E> sublist=new GITLinkedList(ar);
return sublist;
}
最佳答案
为什么不返回一个扩展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 上工作
关于java - 子列表实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10062049/