I was solving some questions for my OCA prepration. I found this problem at Oracle's website listing sample questions for exam.
Code:
public class MyStuff {
MyStuff(String n) { name = n; }
String name;
public static void main(String[] args) {
MyStuff m1 = new MyStuff("guitar");
MyStuff m2 = new MyStuff("tv");
System.out.println(m2.equals(m1));
}
public boolean equals(Object o) {
MyStuff m = (MyStuff)o;
if(m.name != null) return true;
return false;
}
}
Question:
What is the result?
The output is "true" and MyStuff fulfills the Object.equals() contract.
The output is "false" and MyStuff fulfills the Object.equals() contract.
The output is "true" and MyStuff does NOT fulfill the Object.equals() contract.
The output is "false" and MyStuff does NOT fulfill the Object.equals() contract.
Compilation fails.
An exception is thrown at run time.
Answer is-
3. The output is "true" and MyStuff does NOT fulfill the Object.equals() contract.
I understand how, and why the output is true, but what I am not getting is that How come it does not fullfill the Object.equals() contract, and what exactly is a "Contract" in Java, and what if we don't abide by it?
The equals method implements an equivalence relation on non-null object references:
It is reflexive: for any non-null reference value x, x.equals(x) should return true.
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
For any non-null reference value x, x.equals(null) should return false.
The below method doesn't fulfill this obligation For any non-null reference value x, x.equals(null) should return false.
public boolean equals(Object o) {
MyStuff m = (MyStuff)o;
if(m.name != null) return true;
return false;
}
This will throw a ClassCastException , if o is null , it should ideally return false.
The contract here has the english meaning as well as the convention of "design by contract". The contract in terms of equals() and hashcode() method is found on the javadocs of Object - I am assuming you have read it.
The wikipedia page is a must read for better understanding of "design by contract" paradigm. In Java, interfaces are typically defined to establish a contract which the implementation classes then have to abide by.
User scorpion answered what a contract is.
if you don't full fill the contract, them your code might behave unexptected e.g when you use java Collections. I remember one of my collegues said: This java Collection has a bug, it does not work. But the bug was his equals method, not working togehther with hashcode()
Related
I have below code written:
public class Test{
int a;
public static void main(String[] args){
Test t1 = new Test();
Test t2 = new Test();
if(!t1.equals(t2))
System.out.println("They're not equal");
if(t1 instanceof Test)
System.out.println("True");
}
}
And here is the Output:
They're not equal
True
I even tried to assign the same value to instance variable 'a' of both these objects, like below,
t1.a = 10;
t2.a = 10;
Still the same output.
May I know when the t1.equals(t2) will return True?
How does the equals() method work on objects?
By default, calling equals execute the equals method of Object class, which returns true only when you are comparing an instance to itself.
You can override this method in other classes, so that equals would return true when the properties of both objects are equal.
For example :
#Override
public boolean equals(Object other)
{
if (other == null)
return false;
if (other instance of Test) {
Test t = (test) other;
return this.a == t.a;
}
return false;
}
Adding this method to your Test class would change the result of t1.equals(t2) to true.
The Object.equals(Object) Javadoc says (in part),
Indicates whether some other object is "equal to" this one.
The equals method implements an equivalence relation on non-null object references:
It is reflexive: for any non-null reference value x, x.equals(x) should return true.
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
For any non-null reference value x, x.equals(null) should return false.
For your code you could override equals like
#Override
public boolean equals(Object o) {
if (o instanceof Test) {
return ((Test) o).a == a;
}
return false;
}
The default implementation of Object.equals treats two objects as equal only if they are exactly the same object, not just the same contents but the same reference.
Objects can have different implementations of equals, but you must program them explicitly: if you want to check that all fields are equal, you must actually write an equals implementation that checks that.
I was wondering which are the cases where a variable in java could not be equal
(using the equals() method) to itself.
I am not talking object here but the variable itself
(as long as the code compiles and return false when calling equals).
The only situation in which it does that I found so far is:
public class A {
public static void main(String args[]){
A a = new A();
System.out.println(a.equals((a = null)));
}
}
Is there any other case in which a.equals(a) would return false?
EDIT: no overriding of equals() is allowed but you can Modify (cast, inherit) a as much as you want as long as the variable a compare itself in the end.
It could return false in multithreaded contexts, even with an equals implementation that fulfills the equals contract:
class Test {
public static final A a = new A();
public static void main(String... args) throws Exception {
new Thread() {
#Override
public void run() {
while (true) {
a.x += 1;
}
}
}.start();
Thread.sleep(10);
System.out.println(a.equals(a)); // <---
}
}
class A {
int x;
#Override
public boolean equals(Object o) {
return (o instanceof A) && ((A)o).x == x;
}
}
false
From the Object documentation of Oracle:
public boolean equals(Object obj)
Indicates whether some other object is "equal to" this one.
The equals method implements an equivalence relation on non-null object references:
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
For any non-null reference value x, x.equals(null) should return false.
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
Parameters:
obj - the reference object with which to compare.
Returns:
true if this object is the same as the obj argument; false otherwise.
So coming back to your question and analizing the documentation
It's false when a.equals(null); and when a and b (Objects of the classes A and B respectively) are compared, i.e. a.equals(b) will return false too.
In other cases it's true, because of:
It is reflexive: for any non-null reference value x, x.equals(x) should return true.
It clearly says that: not null reference to x (or a in this case):
a.equals(a); will be true
I support khale's and Frakcool's reply. In addition to that if you just need another case to get false try
System.out.println(a.equals((a = new A())));
The assignment essentially returns what is being assigned and that will equate to false if its not the calling object itself.
I don't think there is a way we can get this done, since calling equals to itself is always true. Let me explain what you're trying to achieve.
String foo = "";
bool a = foo.equals(foo); // Here true, the easy one
foo = "some value";
bool b = foo.equals(foo); // Here true, since it's changed and then compared to itself again
bool c = foo.equals(foo="some other value"); // Here should be true again, since the compiler takes first the arguments, makes the assignation, and then makes the equals method execution, so in compiler what happens is:
// 1. Make foo = "some other value"
// 2. Compares foo with foo
// Foo is already changed, so is equals to itself
I haven't tried myself, but that's what should happen.
If for some reason compiler breaks in line bool c = ... it's because equals does not receive String instantiation as a String parameter.
With a correctly implemented .equals(), a.equals(a) will never be false.
Passing an expression to the equals method:
a.equals(a = null);
is no more special than:
a.equals(b); or a.equals(null);
You're just comparing two different values, stuffing an expression into the equals calls doesn't change that.
A very interesting case is the one where you have a boxed Float, consider this code:
Float alpha = +0.0f;
Float beta = -0.0f;
boolean equal = alpha.equals(beta);
System.out.println("Equal: " + equal);
boolean equality = alpha.floatValue() == beta.floatValue();
System.out.println("Equality: " + equality);
This will print true for the first one and false for the second.
The opposite is true of the case of Float.NaN.
Lets see we have 2 references to instances of a user-defined class, a and b in Java.
Can there ever be a situation where
a == b but a.equals(b) return false?
Sure! The implementation of .equals() is completely up to the class, so I could write:
class Foo
public boolean equals(Object other) {
return false;
}
}
Now it doesn't matter what two instances you pass — even the exact same instance twice — I'm always going to say they're not equal.
This particularly setup is silly, but it illustrates that you can get a false result from .equals() for the same object twice.
Note that we're talking here about what can happen, not what should. No class should ever implement a .equals method that claims an object isn't equal to itself. For trusted code, it's reasonable to assume this will never happen.
if a == b then a.equals(b) should be true. And if a.equals(b) then maybe a == b but not necessarily.
The == operator just test if both are referencing the same object. While equals executes a logic that you implemented. The last one can be overridden the first one is an operator from the language, and such as cannot be overridden in Java.
References
what is the difference between == operator and equals()? (with hashcode() ???)
From java.lang.Object documentation:
The equals method implements an equivalence relation on non-null
object references:
It is reflexive: for any non-null reference value x, x.equals(x) should return true.
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns
true.
It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then
x.equals(z) should return true.
It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or
consistently return false, provided no information used in equals
comparisons on the objects is modified.
For any non-null reference value x, x.equals(null) should return false.
Yes, just overload equals to do something silly. e.g.
class Foo {
#Override
boolean equals(Object rhs) { return false; }
}
It is obviously possible to write code that does this, as other answers have pointed out.
However, it is also always a logical error in the code, since it violates the implicit general contract of the equals() function.
An object should always be equal to itself, so if (a==b) then a.equals(b) should always return true.
Ya we can overload the .equals function to give the desired output. but there is no case where == returns true while .equals returns false.
class s {
int a;
}
class dev {
public static void main(String args[]) {
s a = new s();
s b = new s();
System.out.println(a == b);
System.out.println(a.equals(b));
}
}
Output
false
false
Yes, easily:
public class Wrong{
public boolean equals(Object other)
{
return false;
}
}
Of course, this completely breaks the normal rules for implementing .equals() - see the Javadocs - but there's nothing to stop you other than good sense.
The equals method can be overridden in order to provide custom functionality other than the typical == method. Also, some types such as Strings will not return true when using the == method. You have to use .equals or .compareTo (equal when returns 0).
This should provide some additional help
package com.stackOverFlow;
import java.util.Date;
public class SampleClass {
public static int myint = 1;
private SampleClass() {
};
public Integer returnRandom() {
return myint++;
}
private static SampleClass _sampleClass;
public static SampleClass getInstance() {
if (_sampleClass == null) {
_sampleClass = new SampleClass();
}
return _sampleClass;
}
#Override
public boolean equals(Object other) {
if (this.returnRandom().equals(((SampleClass) other).returnRandom())) {
return true;
}
return false;
}
}
package com.stackOverFlow;
public class Run {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SampleClass a = SampleClass.getInstance();
SampleClass b = SampleClass.getInstance();
if(a==b){
System.out.println("references are same as they are pointing to same object");
if(!a.equals(b)){
System.out.println("two random number Instance will never be same");
}
}
}
}
You can understand this by Practical example. where a singeleton class will always return you same reference, and you can override equals method to get something that is not class variable. example a value from database at two particular time , or a random number. Hope that clears your case
I have created two StringBuffer as follows
StringBuffer buffer1 = new StringBuffer("Text");
StringBuffer buffer2 = new StringBuffer(buffer1);
If Compare those StringBuffer with equals method then it returned false?
if (buffer1.equals(buffer2))
System.out.println("true");
else
System.out.println("false");
equals() compares the content of the string.So, i dont know what is the reason for returning false here...
Please Guide me get out of this issue?
StringBuffer.equals() does NOT compare the string contents. You have to do toString().equals().
You are comparing objects not text.
buffer1 is different form buffer2
read JDK reference of equals method
The equals method implements an equivalence relation on non-null object references:
It is reflexive: for any non-null reference value x, x.equals(x) should return true.
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
For any non-null reference value x, x.equals(null) should return false.
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
You should use toString().
if (buffer1.toString()
.equals(buffer2.toString()))
System.out.println("true");
else
System.out.println("false");
I´ve often found an equals method in different places. What does it actually do? Is it important that we have to have this in every class?
public boolean equals(Object obj)
{
if (obj == this)
{
return true;
}
if (obj == null)
{
return false;
}
if (obj instanceof Contact)
{
Contact other = (Contact)obj;
return other.getFirstName().equals(getFirstName()) &&
other.getLastName().equals(getLastName()) &&
other.getHomePhone().equals(getHomePhone()) &&
other.getCellPhone().equals(getCellPhone());
}
else
{
return false;
}
}
It redefines "equality" of objects.
By default (defined in java.lang.Object), an object is equal to another object only if it is the same instance. But you can provide custom equality logic when you override it.
For example, java.lang.String defines equality by comparing the internal character array. That's why:
String a = new String("a"); //but don't use that in programs, use simply: = "a"
String b = new String("a");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
Even though you may not need to test for equality like that, classes that you use do. For example implementations of List.contains(..) and List.indexOf(..) use .equals(..).
Check the javadoc for the exact contract required by the equals(..) method.
In many cases when overriding equals(..) you also have to override hashCode() (using the same fields). That's also specified in the javadoc.
Different classes have different criteria for what makes 2 objects "equal". Normally, equals() returns true if it is the same Object:
Object a = new Object();
Object b = new Object();
return(a.equals(b));
This will return false, eventhough they are both "Object" classes, they are not the same instance. a.equals(a) will return true.
However, in cases like a String, you can have 2 different instances but String equality is based on the literal characters that make up those Strings:
String a = new String("example");
String b = new String("example");
String c = new String("another");
a.equals(b);
a.equals(c);
These are all different instances of String, but the first equals will return true because they are both "example", but the 2nd will not because "example" isn't "another".
You won't need to override equals() for every class, only when there is a special case for equality, like a class that contains 3 Strings, but only the first String is used for determining equality. In the example you posted, there could have been another field, description which could be different for 2 different "Contacts", but 2 "Contacts" will be considered equal if those 4 criteria match (first/last name, and home/cell phone numbers), while the description matching or not matching doesn't play into whether 2 Contacts are equal.
Aside from everything given by Bozho, there are some additional things to be aware of if overriding equals:
something.equals(null) must always return false - i.e. null is not equal to anything else. This requirement is taken care of in the second if of your code.
if it is true that something == something else, then also something.equals(something else) must also be true. (i.e. identical objects must be equal) The first if of your code takes care of this.
.equals SHOULD be symetric for non-null objects, i.e. a.equals(b) should be the same as b.equals(a). Sometimes, this requirement breaks if you are subclassing and overriding equals in the parent-class and in the subclass. Often equals contains code like if (!getClass().equals(other.getClass())) return false; that at least makes sure that a diffrent object type are not equal with each other.
If you override equals you also MUST override hashCode such that the following expression holds true: if (a.equals(b)) assert a.hashCode() == b.hashCode(). I.e. the hash code of two objects that are equal to each other must be the same. Note that the reverse is not true: two objects that have the same hash code may or may not be equal to each other. Ususally, this requirement is taken care of by deriving the hashCode from the same properties that are used to determine equality of an object.
In your case, the hashCode method could be:
public int hashCode() {
return getFirstName().hashCode() +
getLastName().hashCode() +
getPhoneHome().hashCode() +
getCellPhone().hashCode();
}
If you implement Comparable that compares two objects if they are smaller, larger, or equal to each other, a.compareTo(b) == 0 should be true if and only if a.equalTo(b) == true
In many IDEs (e.g. Eclipse, IntelliJ IDEA, NetBeans) there are features that generate both equals and hashCode for you, thereby sparing you of tedious and possibly error-prone work.
The equals method is used when one wants to know if two objects are equivalent by whatever definition the objects find suitable. For example, for String objects, the equivalence is about whether the two objects represent the same character string. Thus, classes often provide their own implementation of equals that works the way that is natural for that class.
The equals method is different from == in that the latter tests for object identity, that is, whether the objects are the same (which is not necessarily the same as equivalent).
It enables you to re-define which Objects are equal and which not, for example you may define that two Person objects as equal if the Person.ID is the same or if the Weight is equal depending on the logic in your application.
See this: Overriding the java equals() method quirk
By default, the Object class equals method invokes when we do not provide the implementation for our custom class. The Object class equals method compares the object using reference.
i.e. a.equals(a); always returns true.
If we are going to provide our own implementation then we will use certain steps for object equality.
Reflexive: a.equals(a) always returns true;
Symmetric: if a.equals(b) is true then b.equals(a) should also be true.
Transitive: If a.equals(b), b.equals(c) then a.equals(c) should be true/false according to previous 2 result.
Consistent: a.equals(b) should be the same result without modifying the values of a and b.
Note: default equals method check the reference i.e. == operator.
Note: For any non-null reference value a, a.equals(null) should return
false.
public class ObjectEqualExample{
public static void main(String []args){
Employee e1 = new Employee(1, "A");
Employee e2 = new Employee(1, "A");
// if we are using equals method then It should follow the some properties such as Reflexive, Symmetric, Transitive, and constistent
/*
Reflexive: a.equals(a) always returns true;
Symmetric: if a.equals(b) is true then b.equals(a) should also be true.
Transitive: If a.equals(b), b.equals(c) then a.equals(c) should be true/false according to previous 2 result.
Consistent: a.equals(b) should be the same result without modifying the values of a and b.
Note: default equals method check the reference i.e. == operator.
Note: For any non-null reference value a, a.equals(null) should return false
*/
System.out.println(e1.equals(e1));
System.out.println(e1.equals(e2));
}
}
class Employee {
private int id;
private String name;
#Override
public String toString() {
return "{id ="+id+", name = "+name+"} ";
}
#Override
public boolean equals(Object o) {
// now check the referenc of both object
if(this == o) return true;
// check the type of class
if(o == null || o.getClass() != this.getClass()) return false;
// now compare the value
Employee employee = (Employee)o;
if(employee.id == this.id && employee.name.equals(this.name)) {
return true;
} else return false;
}
public int hashCode() {
// here we are using id. We can also use other logic such as prime number addition or memory address.
return id;
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
One more thing, maps use the equals method to decide if an Object is present as a key. https://docs.oracle.com/javase/8/docs/api/java/util/Map.html