What is the difference between ArrayBuffer and Array

前端 未结 4 1766
悲&欢浪女
悲&欢浪女 2020-12-14 18:16

I\'m new to scala/java and I have troubles getting the difference between those two.

By reading the scala doc I understood that ArrayBuffer are made to

4条回答
  •  一生所求
    2020-12-14 18:48

    Another difference is in term of reference and value equality

    Array(1,2) == Array(1,2)              // res0: Boolean = false
    ArrayBuffer(1, 2) == ArrayBuffer(1,2) // res1: Boolean = true
    

    The reason for the difference is == routes to .equals where Array.equals is implemented using Java's == which compares references

    public boolean equals(Object obj) {
      return (this == obj);
    }
    

    whilst ArrayBuffer.equals compares elements contained by ArrayBuffer using sameElements method

      override def equals(o: scala.Any): Boolean = this.eq(o.asInstanceOf[AnyRef]) || (
        o match {
          case it: Seq[A] => (it eq this) || (it canEqual this) && sameElements(it)
          case _ => false
        }
      )
    

    Similarly, contains behaves differently

    Array(Array(1,2)).contains(Array(1,2))                   // res0: Boolean = false
    ArrayBuffer(ArrayBuffer(1,2)).contains(ArrayBuffer(1,2)) // res1: Boolean = true
    

提交回复
热议问题