当前位置:网站首页>Scala equality

Scala equality

2022-06-22 16:56:00 ZH519080

stay scala Everything in is the object !!!

java Compare two objects in / Whether the attributes are equal :

/** stay java in ,==  Only to java Object references , Object references the same address ( Same location in memory ) Then return to true ;
  *  and equals Is to compare whether the values of two fields are equal , If the values are equal, return true
  *
  *  But when comparing Array perhaps Seq when , Use sameElements Method */
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 // Throw out java.lang.NullPointerException abnormal 
  null equals null // Throw out java.lang.NullPointerException abnormal 

  p1 == p2 //=true
  p1 == p3 //=false
  /** stay scala in ,equals  And  ==  Exactly the same as , They just test whether the values are equal */
  p1 == null //=false
  null == p1 //=false
  null == null //=true, There are compilation warnings 


  p1 eq(p2)  //=true
  p1 eq p3 //=false
  p1 eq null //=false
  null eq(p2) //=false
  null eq(null)  //true , There are compilation warnings 

  /**eq  Is to compare whether references are equal , When two objects point to the same location in memory, it returns true
    *  among  ne Methods and eq contrary ,ne  Equivalent to !(object1 eq object2)*/
}

But when scala in Array perhaps Seq It is best to use... To compare equality sameElements idea

/**
  * @author E-mail:[email protected]  Zhu Haichuan  
  * @date  Creation time :2016/11/25 21:54
  * @declare  Related instructions : Array 、 Sequence equality comparison 
  */

object ArraySeqsameElements {

  def main(args: Array[String]): Unit = {
    val arraySeqsameElements = new ArraySeqsameElements
    arraySeqsameElements.arrayEquals
  }
}

class ArraySeqsameElements {

  def arrayEquals: Unit ={

    /** Compare Array Using an array sameElements Method */
    val array1 = Array(1,2,3)
    val array2 = Array(1,2,3)

    val bool1 = array1 == array2  // = false

    println(" Use == Compare array equality :"+bool1)

    val bool2 = array1 sameElements(array2)
    println(" Use sameElements Compare equality :"+bool2)



    /** If comparing arrays , It is better to compare with sequence */
    val list1 = List(1,2,3)
    val list2 = List(1,2,3)

    val bool3 = list1 == list2  //=true
    val bool4 = list1 sameElements(list2) //=true
  }
}

 

原网站

版权声明
本文为[ZH519080]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221523254640.html