subclasses中AbstractListclass的removeRange方法有什么用
What is the use of removeRange method of AbstractList class in subclasses
在有效Java中,声明
removeRange method is of no interest to end users of a List
implementation. It is provided solely to make it easy for subclasses
to provide a fast clear method on sublists. In the absence of the
removeRange method, subclasses would have to make do with quadratic
performance when the clear method was invoked on sublists or rewrite
the entire subList mechanism from scratch—not an easy task!
请看这个link。最后一段。它说在 removeRange 方法的 absence 中,子类将不得不使用 quadratic performance。
请解释作者为什么这么说。
In the absence of the removeRange
method, subclasses would have to make do with quadratic performance when the clear method was invoked on sublists
作者假设实现必须为范围的每个元素调用 remove
。在某些实现中,例如 ArrayList
s,remove
必须复制元素被删除后的所有内容,其复杂度为 O(n)。假设范围大小为 r
,循环实现的总体复杂度为 O(n*r),它是二次方的。
特定于 ArrayList
的 removeRange
的实现复杂度为 O(n),因为您可以在单个循环中将其复制到新位置。
AbstractList
已经提供了 subList(int from, int to)
的默认实现。此默认子列表的 clear()
方法只是在其父列表上调用 removeRange(...)
。
如果没有 removeRange(...)
,子列表将不得不使用迭代器,重复调用 next()
和 remove()
。但是通过 Iterator.remove()
删除元素可能具有线性性能 - 例如ArrayList
每次删除元素时都必须左移其内部数组中的所有后续元素。重复调用 linear 方法会导致 quadratic 性能。
注意:AbstractList
中的removeRange(...)
实现默认使用迭代器。因此子类应该覆盖它以提供更高性能的实现(如果可用)。
优点:为了优化性能,子类只需要实现removeRange
,并且可以保留subList(...)
的默认实现。
在有效Java中,声明
removeRange method is of no interest to end users of a List implementation. It is provided solely to make it easy for subclasses to provide a fast clear method on sublists. In the absence of the removeRange method, subclasses would have to make do with quadratic performance when the clear method was invoked on sublists or rewrite the entire subList mechanism from scratch—not an easy task!
请看这个link。最后一段。它说在 removeRange 方法的 absence 中,子类将不得不使用 quadratic performance。
请解释作者为什么这么说。
In the absence of the
removeRange
method, subclasses would have to make do with quadratic performance when the clear method was invoked on sublists
作者假设实现必须为范围的每个元素调用 remove
。在某些实现中,例如 ArrayList
s,remove
必须复制元素被删除后的所有内容,其复杂度为 O(n)。假设范围大小为 r
,循环实现的总体复杂度为 O(n*r),它是二次方的。
特定于 ArrayList
的 removeRange
的实现复杂度为 O(n),因为您可以在单个循环中将其复制到新位置。
AbstractList
已经提供了 subList(int from, int to)
的默认实现。此默认子列表的 clear()
方法只是在其父列表上调用 removeRange(...)
。
如果没有 removeRange(...)
,子列表将不得不使用迭代器,重复调用 next()
和 remove()
。但是通过 Iterator.remove()
删除元素可能具有线性性能 - 例如ArrayList
每次删除元素时都必须左移其内部数组中的所有后续元素。重复调用 linear 方法会导致 quadratic 性能。
注意:AbstractList
中的removeRange(...)
实现默认使用迭代器。因此子类应该覆盖它以提供更高性能的实现(如果可用)。
优点:为了优化性能,子类只需要实现removeRange
,并且可以保留subList(...)
的默认实现。