当前位置:网站首页>scala的相等性
scala的相等性
2022-06-22 15:24:00 【ZH519080】
在scala中一切都是对象!!!
java中比较两个对象/属性是否相等:
/**在java中,== 只会对java对象引用进行比较,对象引用的地址相同(内存中同一个位置)则返回true ; * 而equals是比较两个字段的值是否相等,若值相等则返回true * * 不过当比较Array或者Seq时,使用sameElements方法*/
class EqualEq {
case class Person(firstName: String,lastName: String,age: Int)
val p1 = Person("Dean","Wampler",29)
val p2 = Person("Dean","Wampler",29)
val p3 = Person("Buck","Trends",30)
p1 equals p2 // =true
p1 equals(p3) //=false
p1 equals null //=false
null equals p1 //抛出java.lang.NullPointerException异常
null equals null //抛出java.lang.NullPointerException异常
p1 == p2 //=true
p1 == p3 //=false
/**在scala中,equals 与 == 完全一样,都只是测试其值是否相等*/
p1 == null //=false
null == p1 //=false
null == null //=true,有编译警告
p1 eq(p2) //=true
p1 eq p3 //=false
p1 eq null //=false
null eq(p2) //=false
null eq(null) //true ,有编译警告
/**eq 是比较引用是否相等,当两个对象指向内存中同一个位置则返回true
* 其中 ne方法与eq相反,ne 就相当于!(object1 eq object2)*/
}但是当scala中Array或者Seq比较是否相等最好使用sameElements想法
/**
* @author E-mail:[email protected] 朱海川
* @date 创建时间:2016/11/25 21:54
* @declare 相关说明:数组、序列相等比较
*/
object ArraySeqsameElements {
def main(args: Array[String]): Unit = {
val arraySeqsameElements = new ArraySeqsameElements
arraySeqsameElements.arrayEquals
}
}
class ArraySeqsameElements {
def arrayEquals: Unit ={
/**比较Array数组使用sameElements方法*/
val array1 = Array(1,2,3)
val array2 = Array(1,2,3)
val bool1 = array1 == array2 // = false
println("使用==比较数组相等性:"+bool1)
val bool2 = array1 sameElements(array2)
println("使用sameElements比较相等性:"+bool2)
/**若比较数组,最好用序列比较*/
val list1 = List(1,2,3)
val list2 = List(1,2,3)
val bool3 = list1 == list2 //=true
val bool4 = list1 sameElements(list2) //=true
}
}
边栏推荐
猜你喜欢

什么是 SAP ABAP? 类型、ABAP 完整形式和含义

JSP learning (2) -- JSP script elements and instructions

【C语言】库函数qsort的使用

How to add a "security lock" to the mobile office of government and enterprises?

jsp学习之(三)--------- jsp隐式对象
![[wechat applet to obtain the height of custom tabbar] is absolutely available!!!](/img/ed/7ff70178f03b50cb7bec349c1be5e0.png)
[wechat applet to obtain the height of custom tabbar] is absolutely available!!!

SLAM十四讲之第6讲--非线性优化

Parts beyond the text are indicated by ellipsis

SAP ABAP BAPI-016

面对默认导入失败的情况
随机推荐
Interview knowledge points
SAP ABAP 中的模块化:宏、子程序和功能模块 -04
大话局部性原理
Add a millennial sign to a number (amount in millennia)
长安链使用技巧总结
Interface (optimization type annotation)
【C语言深度解剖】关键字if&&else&&bool类型
Prometheus监控之Consul监控 [consul-exporter]
LeetCode_回溯_动态规划_中等_131.分割回文串
5. reading and writing of documents (students)
SAP ABAP data types, operators and editors-02
二叉树练习第二弹
【C语言】库函数qsort的使用
Test for API
VHEDT业务发展框架
首个赛博格人陨落背后:科技与渐冻症的极限赛跑
SAP web service 无法使用 SOAMANAGER 登陆到SOA管理页面
Test for API
What is SAP ABAP? Type, ABAP full form and meaning
[C language] deeply analyze the relationship between pointer and array