Time complexity of JavaConverters asScala method

狂风中的少年 提交于 2019-11-30 22:21:00

问题


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

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:

Where can I get information on the complexity (time and space) of the JavaConverters?


回答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.

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
}

Also note that converting Java collection to Scala and then back to Java yields the original collection, not double-wrapper.



来源:https://stackoverflow.com/questions/8517636/time-complexity-of-javaconverters-asscala-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!