scala学习之⾃定义排序scala⾃定义排序
⾃定义排序两种⽅式:
**1:实现继承ordered
2:new ordering**
1:new ordering
loi//排序⽅法⼀
def sortgather(): Unit = {
println(“集合排序----⽅法2”)
val t = mutable.SortedSet(new person(“zs”, 33),
身份证查四六级new person(“ls”, 23),
dhaka
new person(“ws”, 43))(new Ordering {
override def compare(x: person, y: person): Int = {
var sort01 = pareTo(y.age) //排序1t
if (sort01 == 0) {
sort01 = pareTo() //排序规则2
什么叫电子邮件地址}
sort01
}
})
println(t)
}
//构造
class person {
//排序⽅法⼀:继承ordered
var name: String = _
var age: Int = _
nubbdef this(name: String, age: Int) {
this()
excitedabout= name
this.age = age
}
detailly
override def toString: String = + this.age
framet}
2:实现继承ordered
def sortgather(): Unit ={
println("集合排序----⽅法1")
val t =mutable.SortedSet(new person("zs",33),
fsfnew person("ls",23),
new person("ws",43))
println(t)
}
}
class person extends Ordered[person]{//排序⽅法⼀:继承ordered var name:String= _
var age:Int= _
def this(name:String,age:Int){
this()
this.name=name
this .age=age
}
//重写tostring,否则为地址greenlantern
override def toString: String = this.name+this.age
override def compare(that: person) = {
var sort01=pareTo(that.age)//排序1t
if(sort01==0){
sort01=pareTo()//排序规则2
}
sort01
}
}