Practice: Object v. Reference Equality

I have two questionsđŸ„č

  1. The system says:

“Your submission contains unexecuted code:
You have 1 more lines of unexecuted code than the solution, which is more than the limit of 0.”

but I campared my code with the walkthrough and they look the same. I can’t figure out what‘s wrong.

  1. How can we be sure the input object o1 and o2 have overrided .equals() methos? if o1 and o2 happen to not override .equals() method, won’t .equals() in line 7 just work as ==? I can’t find another way around .equals() though, I’m not sure why .equals() works.

In case you haven’t figured it out:

  1. You don’t need the else block. So instead of
    else { return -1 } you could simply write return -1

  2. Could you provide me with the question description?

  1. I’m not sure if this is a bug of the test cases or not, but if you omit o2 == null in your first else if statement, the program executes without that error.

  2. To answer your second question, we don’t actually have to know whether or not an object has overridden the .equals() method. This is because 1. every object inherits a .equals() method and 2. your program does enough to test for scenarios in which the inputted objects either have an overridden method or not.

In cases where neither object has an overridden .equals() method, you are correct to say that .equals() would function in the same way as ==. In such cases, this makes the o1.equals(o2) check redundant because it would be the same as o1 == o2. This also means that the program would never return a value of 1, and that is ok! This is because it still is consistent with the goal of our program, which is to check whether or not the references or objects are equal.

We know what it means for references to be equal, but what it means for objects to be equal is arbitrary and depends on the developers behind the class. If the developers don’t override the .equals() method, then it can be viewed as them saying that the only way to check for if their objects are equal is through their references. So if the references aren’t equal, then it can be implied that the objects aren’t equal either.

The if o1.equals(o2) check can actually be viewed as an additional check to see whether or not the two objects have an overridden .equals() method. If the developers behind the class believe that their objects can be equal beyond their references (such as when you use .equals() to check whether or not the contents of two strings are equal), then the program can return 1 even if the references are different.

I hope this can clear up some of your confusion (instead of causing more lol). If you have any additional questions, please let me know! :smiley:

There was a bug in the test cases that wasn’t checking for both null cases. That should be fixed.