Why doesn't "crime.getId() == id" work?


#1

In this chapter my app would crash due to no crime being returned from getCrime(UUID id). As it turns out, within my getCrime() method, I used == instead of .equals(). This results in me always receiving null.

public Crime getCrime(UUID id) {

    for (Crime crime : mCrimes) {
        if (crime.getId() == id) {
            return crime;
        }
    }

    return null;
}

Changing it to .equals() completely fixes my app.

So I know there’s a difference between == and .equals(), but I’m still confused as to why == didn’t work. From my understanding, if two references are referencing the same object, then == should be true.

So I’m assuming at some point these became different objects, but I don’t know where.

Our CrimeLab created a bunch of crimes, and within each Crime’s constructor they created and stored their UUIDs. From that moment on, I don’t know where things went wrong. We’ve retrieved and passed along the UUIDs from the crime objects. Shouldn’t the UUID we pass into getCrime(UUID id) literally be the same exact UUID as one of the Crimes?

Thanks


#2

Java is a pass by value language :face_with_monocle: So, when you test for equality between data objects, it is imperative that you actually check the equality of the underlying data contained within the object as opposed to checking for the equality of the hashcode()(the integer value to which the memory address of the object is mapped to), which is what you are achieving with the == check.

The below compares the memory address of where the number 12 is stored, which will always return false because these objects are stored in different places in the memory.

Object a = 12;
Object b = 12;
a == b // This will return false

The below actually compares the underlying data of each of the object.

Object a = 12;
Object b = 12;
a.equals(b) // Compares whether 12 == 12

I have explained as lucidly as possible. When I get some reading resources pertaining to this question and also explaining the above concept in detail, I’ll post here. In the meanwhile, happy coding/learning :+1::grin:


#3

Thanks for the response.

I believe I found the point where our UUID becomes a new UUID. Parceling it in our arguments bundle and unparcelling it is what makes it a whole new UUID. Therefore the argument we retrieve and pass into getCrime() doesn’t have the same memory address as any of the Crimes’ UUIDs.

If you cheat and just pass in a Crime’s UUID directly from our CrimeLab, my bad implementation works.

Thanks!


#4

you are welcome :+1::grin: