【发布时间】:2014-12-22 18:17:52
【问题描述】:
我想实现一个类似于 subList(a,b) 的方法,但是当 a>b 时有效。 subList(a,b) 和 subList(b,a) 应该返回相同范围的列表视图,但迭代和编号方式不同。在 a>b 的情况下,view 应该被颠倒。有可能吗?
我现在的解决方案非常原始。第一个问题是 subList(a,b) 在 a>b 的情况下没有相应地调整编号(对于 remove 或 get 方法的使用)。但更重要的是,反转的 List 视图实际上是这里的副本而不是实际视图,我什至不知道如何解决。
@SuppressWarnings("serial")
class ReverseLinkedList <T> extends LinkedList<T>
{
ReverseLinkedList(final List<T> l)
{
super(l); // problem, I want a view not a copy
}
@Override
public Iterator<T> iterator()
{
return new Iterator<T>()
{
ListIterator<T> listIter = listIterator(size());
public boolean hasNext()
{
return listIter.hasPrevious();
}
public T next()
{
return listIter.previous();
}
public void remove()
{
listIter.remove();
}
};
}
}
@SuppressWarnings("serial")
class CleverList<T> extends LinkedList<T>
{
@Override
public List<T> subList(int fromIndex, int toIndex)
{
if ( fromIndex < toIndex )
{
return super.subList(fromIndex, toIndex);
}
else
{
return new ReverseLinkedList<T>(super.subList(toIndex-1,fromIndex-1));
}
}
}
目前如何运作:
CleverList<Integer> list = new CleverList<Integer>();
for ( int i=1; i<=10; ++i )
{
list.add(i);
}
List<Integer> listA = list.subList(2,8);
printList(listA);
// "3 4 5 6 7 8 " ok
List<Integer> listB = list.subList(8,2);
printList(listB);
// "7 6 5 4 3 2 " ok
listB.remove(2);
printList(listB);
// "7 6 5 3 2 " not ok, the point was to remove "5"
printList(list);
// "1 2 3 4 5 6 7 8 9 10 " not ok, nothing was removed
【问题讨论】:
-
您的课程是否必须扩展
LinkedList还是只实现List? -
@user2040251 我认为 List 就足够了。不过,我对 LinkedList 扩展有点好奇。
标签: java data-structures collections