Scala replacement for Arrays.binarySearch?

前端 未结 6 1731
故里飘歌
故里飘歌 2020-12-29 03:18

Is there a replacement in Scala for Java\'s int Arrays.binarySearch(Object[] array, object)?

The problem is that Scala\'s Arrays are not covariant, so I

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-29 04:14

    Arrays are funny beasts. If you try the code in the example provided with 'ObjectArrayTools' with this:

    Array(1, 2, 3, 4, 5).binarySearch(3)
    

    You get

    error: value binarySearch is not a member of Array[Int]
              Array(1, 2, 3, 4, 5).binarySearch(3)
    

    For what's going on with Arrays in Scala refer to this document. In any case, you could use this code instead, although it uses Seq instead of Array. However, it has the added bonus of using an Ordering (which just so happens to also be a Java Comparator. So you can customize the ordered behavior if needed.)

    import _root_.scala.collection.JavaConversions._
    import java.util.{Collections, List => JList}
    class SearchableSeq[T](a: Seq[T])(implicit ordering: Ordering[T]) {
        val list: JList[T] = a.toList
        def binarySearch(key: T): Int = Collections.binarySearch(list, key, ordering)
    }
    implicit def seqToSearchable[T](a: Seq[T])(implicit ordering: Ordering[T]) = 
            new SearchableSeq(a)(ordering)
    

    Some examples:

    scala> List(1, 2, 3, 4, 5).binarySearch(3)
    res0: Int = 2
    
    scala> List(1D, 2D, 3D, 4D, 5D).binarySearch(3.5)
    res1: Int = -4
    
    scala> List("a","fish","is","some","thing").binarySearch("bye")
    res2: Int = -2
    

提交回复
热议问题