Question: Single Element Lists Have Same Head But Are Not Equal?

Question

Single Element Lists Have Same Head But Are Not Equal?

Answers 1
Added at 2017-01-04 20:01
Tags
Question

Given two List[A] instances, under what circumstance could the following be true?

list.head == otherList.head // returns true
list.size == 1              // returns true
list.size == otherList.size // returns true

but

list == otherList // returns false
Answers to

Single Element Lists Have Same Head But Are Not Equal?

nr: #1 dodano: 2017-01-04 20:01

If I can cheat and use my own A then this would be an example:

scala> :pa
// Entering paste mode (ctrl-D to finish)

class MyClass(val v: Int)
{
    def ==(that: MyClass): Boolean = true
}

// Exiting paste mode, now interpreting.

defined class MyClass

scala> val l1 = List(new MyClass(1))
l1: List[MyClass] = List(MyClass@36776c32)

scala> val l2 = List(new MyClass(2))
l2: List[MyClass] = List(MyClass@39c87b42)

scala> l1.head == l2.head
res4: Boolean = true

scala> l1.size == l2.size
res5: Boolean = true

scala> l1.size == 1
res6: Boolean = true

scala> l1 == l2
res7: Boolean = false

You don't even need mutable values for this, it is just a trick using my own == method. But this is intentionally malignant, hopefully nobody would write code which would do this.

Edit:

All you need to do is either a) trick/break == like I did with MyClass or, as @2rs2ts pointed out, trick/break the sameElements check (which uses !=) :

def sameElements[B >: A](that: GenIterable[B]): Boolean = {
    val these = this.iterator
    val those = that.iterator
    while (these.hasNext && those.hasNext)
        if (these.next != those.next)
            return false
    !these.hasNext && !those.hasNext
}
Source Show
◀ Wstecz