Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
元组的Scala树集_Scala_Comparable_Treeset - Fatal编程技术网

元组的Scala树集

元组的Scala树集,scala,comparable,treeset,Scala,Comparable,Treeset,我试图在scala中实例化一个树集,在元组上传递一个特定的比较器,如下所示: var heads: java.util.TreeSet[(T, Int)] = new java.util.TreeSet[(T, Int)](new Comparator[(T,Int)] { def compare(o1: (T, Int), o2: (T, Int)): Int = Ordering[(T, Int)].compare(o1, o2) }) 但是,找不到T上的隐式排序。我是否应

我试图在scala中实例化一个树集,在元组上传递一个特定的比较器,如下所示:

  var heads: java.util.TreeSet[(T, Int)] = new java.util.TreeSet[(T, Int)](new Comparator[(T,Int)] {
    def compare(o1: (T, Int), o2: (T, Int)): Int = Ordering[(T, Int)].compare(o1, o2)
  })

但是,找不到T上的隐式排序。我是否应该指定T您可以在
T
的定义中添加
:Ordering
()

方法:

def method[T: Ordering] = {
  var heads: ...
}
上课时间:

class MyClss[T: Ordering] {
  var heads: ...
}

对于可比较的
的每个子类型,都有隐式对象
排序[T]
。但也有许多其他类型的对象。例如,对于
TupleN

,由于要比较元组,还需要指定用于比较的元素,例如,如果要按类型
T
的第一个元素排序:

object Main extends App {
  import java.util.Comparator
  def heads[T: Ordering] = new java.util.TreeSet[(T, Int)](new Comparator[(T,Int)] {
    def compare(o1: (T, Int), o2: (T, Int)): Int = Ordering.by[(T, Int), T](_._1).compare(o1, o2)
  })
  val test = heads[String]
  test.add(("Foo", 42))
  test.add(("Foo", 42))
  test.add(("Bar", 17))
  println(test)
}

这将输出
[(Bar,17),(Foo,42)]

是否有一些特殊原因只使用一个元素进行比较?我不知道有,但也有,所以
排序[(t,Int)]。compare()
也可以工作,如果您想按_1,_2排序。