JavaConverters asScala方法的时间复杂度 [英] Time complexity of JavaConverters asScala method
问题描述
从Scala版本2.9开始,有一个方便的转换器可以通过写下这样的内容将 java.util.List
和其他集合转换为Scala的数据结构:
Starting with Scala version 2.9 there exists a handy converter to convert from java.util.List
and other collections to Scala's data structures by writing something like this:
import scala.collection.JavaConverters._
def scalaVersion = callJavaMethod.asScala
这是一个可爱的小功能,因为它允许人们在与现有Java代码交互时利用Scala的优势。
This is a lovely little feature, as it allows one to exploit the advantages of Scala when interacting with existing Java code.
但是,我不确定所涉及的时间和空间复杂性,并且在官方文档中找不到任何内容,因此,以下问题:
However, I am uncertain about the involved time and space complexity and could not find anything in the official documentation, hence, the following question:
我在哪里可以获得有关JavaConverters复杂性(时间和空间)的信息?
Where can I get information on the complexity (time and space) of the JavaConverters?
推荐答案
各种 JavaConverters
类使用 Adapter 模式进行换行原始Java集合( und erlying
)并提供Scala接口。因此,转换和访问转换后的集合在时间上是恒定的( O(1)
),只会产生很小的开销。
Various JavaConverters
classes are using Adapter pattern to wrap original Java collection (underlying
) and provide Scala interface. Thus both converting and accessing converted collections is constant in time (O(1)
) introducing only minor overhead.
例如,这是 <的完整源代码。 code> JListWrapper :
For instance this is the full source code of JListWrapper
:
case class JListWrapper[A](val underlying : java.util.List[A]) extends mutable.Buffer[A] {
def length = underlying.size
override def isEmpty = underlying.isEmpty
override def iterator : Iterator[A] = underlying.iterator
def apply(i : Int) = underlying.get(i)
def update(i : Int, elem : A) = underlying.set(i, elem)
def +=:(elem : A) = { underlying.subList(0, 0).add(elem) ; this }
def +=(elem : A): this.type = { underlying.add(elem); this }
def insertAll(i : Int, elems : Traversable[A]) = { val ins = underlying.subList(0, i) ; elems.seq.foreach(ins.add(_)) }
def remove(i : Int) = underlying.remove(i)
def clear = underlying.clear
def result = this
}
另请注意,将Java集合转换为Scala然后再转换为Java会生成原始集合集合,而不是双层包装。
Also note that converting Java collection to Scala and then back to Java yields the original collection, not double-wrapper.
这篇关于JavaConverters asScala方法的时间复杂度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!