用 Kotlin 做对比,就是插 Comparable 啦!嫁接这姐,你就可以货比三家。

本文通过Kotlin的Comparable接口,详细介绍了compareTo()、coerceAtLeast()、coerceAtMost()和coerceIn()等方法的使用,并结合BinarySearchTree的应用,展示了如何在Kotlin中进行比较和操作。文章包含多个实例演示,适合面试复习和学习。
摘要由CSDN通过智能技术生成

💪0. 比较神器——Comparable

👸VS👸🏻,🙅Fight!叽里咕噜…
比较这个嗜好,女人们最喜欢,比上比下,比房子比车子,甚至比子女。
👀:在 Kotlin 世界里,你插这个就能比,就是 Comparable 插件 。


🏎️1. 方程 compareTo()

compareTo() 是主打方程,发出比一比的号角。
这个 class 是地主🐢,compareTo( 对手🐰 )。

👧🏻:这不是龟兔赛跑吗?好玩!
🤔:这个比喻不好,不明白,咱还是画圈吧。

介绍个两个免费网上Kotlin 编译器 ——

  • Kotlin Playground 游乐园 —— 这个快👍。
  • JDoodle —— 怪名。现打现用,今天就是用这个面试废了。我不是应聘写手机的吗?考官就考基础。我就琢磨着这是干什么来着,手机只有两个问题,其它全是 order,sort,linked list, binary search,可能银行就喜欢这个。记性不好,明年再来。哈奇😷!

✔️它们好处是现打现用,❌坏处是编译功能缺失。你们谁能写个 AI 补补?

class Circle(val radius: Int): Comparable<Circle> {
    
    private val area: Double = 3.14 * radius * radius
    
    override fun compareTo(other: Circle): Int {
    
        val area2 = other.area
  
        // 对比面积
        if(area == area2){
    
            return 0; 
        } else if(area < area2){
    
            return -1; 
        } 
        return 1; 
    } 
    
    override fun toString(): String {
   
        return "Type(circle) -> radius = $radius, area = $area"
    }
}

fun main(){
    
    val cirs: List<Circle> = listOf(
        Circle(5), Circle(4), Circle(4), Circle(7), Circle(8), Circle(10)) 
  
    println("Is cir1 > cir2? ${
     cirs[0] > cirs[1]}") 
    println("Is cir3 > cir1? ${
     cirs[2] > cirs[1]}")
    println("Is cir3 == cir1? ${
     cirs[2] == cirs[1]}")
}

这个 compareTo 需要覆盖,因为 Comparable 只是个 Interface,骨头也。它要做出三种答复 ——

  • 等于 ⇨ 0
  • 小于 ⇨ -1
  • 大于 ⇨ 1

简单,明快。
结果:

Is cir1 > cir2? true
Is cir3 > cir1? false
Is cir3 == cir1? false

🚝2. 方程 coerceAtLeast() 较大

这是比最小大一点的意思,例子:
coerceAtLeast( 较大 ):

  • 是问我比最小大吗?—— 是就我上,反之最小上。

咱们试试:

    var min = Circle(2) 
    var max = Circle(9) 
    
    println("\nmin: ${
     min}\ncir2: ${
     cirs[1]}")    
    println("Find bigger: cir1 > min? Bigger is ${
     cirs[1].coerceAtLeast(min)}") 

🏃结果:

min: Type(circle) -> radius = 2, area = 12.56
cir2: Type(circle) -> radius = 4, area = 50.24
Find bigger: cir1 > min? Bigger is Type(circle) -> radius = 4, area = 50.24

➕找个大小差不多看看:

    println("\ncir1: ${
     cirs[0]}\ncir2: ${
     cirs[1]}")    
    println("Find bigger: cir1 > cir2? Bigger is ${
     cirs[0].coerceAtLeast(cirs[1])}") 
    println("Find bigger: cir2 > cir1? Bigger is ${
     cirs[1].coerceAtLeast(cirs[0])}") 

🏃结果:

cir1: Type(circle) -> radius = 5, area = 78.5
cir2: Type(circle) -> radius = 4, area = 50.24
Find bigger: cir1 > cir2? Bigger is Type(circle) -> radius = 5, area = 78.5
Find bigger: cir2 > cir1? Bigger is Type(circle) -> radius = 5, area = 78.5

都是较大的胜出,这就是 coerceAtLeast 。


🚈3. 方程 coerceAtMost() 较小

顾名思义,coerceAtMost() 就比最大小点,较小也。

    println("\ncir5: ${
     cirs[4]}\nmax: ${
     max}")    
    println("Find bigger: cir5 > max? Bigger is ${
     cirs[4].coerceAtMost(max)}") 
    println("Find bigger: cir5 > max? Bigger is ${
     max.coerceAtMost(cirs[4])}") 

比对 8 号选手 和 max 选手。

cir5: Type(circle) -> radius = 8, area = 200.96
max: Type(circle) -> radius = 9, area = 254.34
Find bigger: cir5 > max? Bigger is Type(circle) -> radius = 8, area = 200.96
Find bigger: cir5 > max? Bigger is Type(circle) -> radius = 8, area = 200.96

8 号较小胜出。现在看来好像多余,其实不是,思维有点不一样而已。反正又不用我写,用就是了。


🚅4. 方程 coerceIn() 域内

明白不?这个方程当然有一大一小,要不怎么知道是否在队伍内。
例子:

coerceIn( 最小,最大 )

拿来玩玩:

    println("\ncir4: ${
     cirs[3]}\nmin: ${
     min}\nmax: ${
     max}")    
    println("Is cir4 in min and max? ${
     cirs[3].coerceIn(min, max) == cirs[3]}") 

在室吗?🏃🏼

cir4: Type(
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,下面是一个简单的 Kotlin 计算器程序,你可以在 Android Studio 中创建一个新的 Kotlin 项目,然后将以下代码添加到 MainActivity.kt 文件中: ```kotlin import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { var num1 = "" var num2 = "" var operator = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } fun buttonClick(view: View) { if (view is android.widget.Button) { when (view.id) { button0.id -> numberClicked("0") button1.id -> numberClicked("1") button2.id -> numberClicked("2") button3.id -> numberClicked("3") button4.id -> numberClicked("4") button5.id -> numberClicked("5") button6.id -> numberClicked("6") button7.id -> numberClicked("7") button8.id -> numberClicked("8") button9.id -> numberClicked("9") buttonPlus.id -> operatorClicked("+") buttonMinus.id -> operatorClicked("-") buttonMultiply.id -> operatorClicked("*") buttonDivide.id -> operatorClicked("/") buttonClear.id -> clearClicked() buttonEqual.id -> equalsClicked() } } } private fun numberClicked(num: String) { if (operator.isEmpty()) { num1 += num resultTextView.text = num1 } else { num2 += num resultTextView.text = num2 } } private fun operatorClicked(op: String) { operator = op } private fun equalsClicked() { val num1Int = num1.toInt() val num2Int = num2.toInt() var result = 0 when (operator) { "+" -> result = num1Int + num2Int "-" -> result = num1Int - num2Int "*" -> result = num1Int * num2Int "/" -> result = num1Int / num2Int } resultTextView.text = result.toString() num1 = result.toString() num2 = "" operator = "" } private fun clearClicked() { resultTextView.text = "0" num1 = "" num2 = "" operator = "" } } ``` 这个程序使用了 Android Studio 的布局编辑器来创建界面,并使用了 Kotlin 的语法来处理输入和计算逻辑。界面包括一个 TextView 显示计算结果,以及多个 Button 用于输入数字和运算符。当用户点击数字按钮时,程序将数字添加到 num1 或 num2 变量中,具体取决于当前是否有运算符。当用户点击运算符按钮时,程序将运算符保存到 operator 变量中。当用户点击等号按钮时,程序根据当前的运算符执行相应的计算,并将结果显示在 TextView 中。当用户点击清除按钮时,程序将所有变量重置为初始值。 注意:这只是一个简单的示例程序,可能无法满足所有需求。如果需要更复杂的计算器功能,你可能需要编写更多代码来实现。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值