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.
Related
I am writing a pojo , where I am overriding hashcode and equals ,
But my condition for making objects equal is having a OR condition .In this case how to write hashcode ???
For example, I have a pojo, having three fields like aaa,bbb,ccc
and condition of treating equal is , aaa must be equal and either bbb or ccc should be equal.I wrote this in equals overriding section but what to write in hashcode in this case ???
public class POJO {
private String aaa;
private String bbb;
private String ccc;
///How to use or condition here ???????
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((aaa == null) ? 0 : aaa.hashCode());
result = prime * result + ((bbb == null) ? 0 : bbb.hashCode());
return result;
}
//my condition is aaa and (bbb or ccc) should be equal
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
POJO other = (POJO) obj;
if (aaa == null) {
if (other.aaa != null)
return false;
} else if (!aaa.equals(other.aaa))
return false;
if (bbb == null || ccc == null) {
if (other.bbb != null || other.ccc != null)
return false;
//This is the main condition
} else if (!bbb.equals(other.bbb) || !ccc.equals(other.ccc))
return false;
return true;
}
public String getAaa() {
return aaa;
}
public void setAaa(String aaa) {
this.aaa = aaa;
}
public String getBbb() {
return bbb;
}
public void setBbb(String bbb) {
this.bbb = bbb;
}
public String getCcc() {
return ccc;
}
public void setCcc(String ccc) {
this.ccc = ccc;
}
}
Your equals logic is inconsistent, so you can't define a consistent hashCode.
Suppose you have 3 objects with the following values :
aaa bbb ccc
"a1" "b1" "c1"
"a1" "b1" "c2"
"a1" "b2" "c2"
According to your logic, the first object is equal to the second (both the aaa and bbb properties are equal), and the second is equal to the third (both the aaa and ccc properties are equal), but the first is not equal to the third (since both the bbb and ccc properties are not equal). equals must be transitive.
From the Javadoc:
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 contract of hashCode function is the following (from javadoc):
Whenever it is invoked on the same object more than once during an
execution of a Java application, the hashCode method must consistently
return the same integer, provided no information used in equals
comparisons on the object is modified. This integer need not remain
consistent from one execution of an application to another execution
of the same application.
If two objects are equal according to the
equals(Object) method, then calling the hashCode method on each of the
two objects must produce the same integer result.
It is not required
that if two objects are unequal according to the
equals(java.lang.Object) method, then calling the hashCode method on
each of the two objects must produce distinct integer results.
However, the programmer should be aware that producing distinct
integer results for unequal objects may improve the performance of
hash tables.
If your code satisfy the three conditions your code is correct.
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.
I would like to do a deeper String check of Objects to be able to do the following:
List<MyObj> myList = new ArrayList<MyObj>() {{
add(new MyObj("hello"));
add(new MyObj("world"));
}};
System.out.println(myList.contains("hello")); // true
System.out.println(myList.contains("foo")); // false
System.out.println(myList.contains("world")); // true
But getting false on each one with the following full code
/* Name of the class has to be "Main" only if the class is public. */
class Ideone {
public static class MyObj {
private String str;
private int hashCode;
public MyObj(String str) {
this.str = str;
}
public #Override boolean equals(Object obj) {
System.out.println("MyObj.equals(Object)");
if (obj == this) {
return true;
}
if (obj instanceof String) {
String strObj = (String) obj;
return strObj.equals(str);
}
return false;
}
public #Override int hashCode() {
if (hashCode == 0) {
hashCode = 7;
for (int i = 0; i < str.length(); ++i) {
hashCode = hashCode * 31 + str.charAt(i);
}
}
return hashCode;
}
}
public static final MyObj obj1 = new MyObj("hello");
public static final MyObj obj2 = new MyObj("world");
public static void main (String[] args) throws java.lang.Exception {
List<MyObj> myList = new ArrayList<MyObj>() {{
add(obj1);
add(obj2);
}};
System.out.println(myList.contains("hello"));
System.out.println(myList.contains("foo"));
System.out.println(myList.contains("world"));
}
}
If I'm right the List Object should use equals() and hashCode() to evaluate containing Objects.
So I #Override them and check their Strings additionally.
But it never gets into equals() as there's no output MyObj.equals(Object).
java.util.ArrayList#indexOf is used internally in ArrayList for contains().
There is a check,
o.equals(elementData[i])
So there is comparison of string with your object, so String.equals() is invoked for check of equality.
You are not fulfilling the equals contract at all:
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. Yours is not reflexive.
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. Yours is not symmetric.
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. Yours is not transitive
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.
So without respecting the contract for the method you can't expect intended behavior.
Just for example, what guarantees you that equals is going to be called on the object contained in the ArrayList and not in the other way, eg "hello".equals(new MyObj("hello")). You have no guarantees about it but since equals is normally supposed to be symmetric than you shouldn't mind.
As pointed out by others, the problem is that your equals method is never called. When you invoke myList.contains("hello"), ArrayList checks whether "hello".equals(<MyObj>), not the other way around.
Instead, I recommend implementing your equals method properly, so that two MyObject instances with equal value are considered equal, and then create a helper method like this:
public boolean myContains(List<MyObj> list, String value) {
return list.contains(new MyObj(value));
}
List<MyObj> myList = new ArrayList<MyObj>()
is a list of MyObj, so you need to use MyObj while checking myList.contains:
System.out.println(myList.contains(new MyObj("hello")));
System.out.println(myList.contains(new MyObj("foo")));
System.out.println(myList.contains(new MyObj("world")));
You're asking the List to compare a String to a MyObj... They are never going to be "equal". Try a map instead:
Map<String, MyObj> map = new HashMap<String, MyObj>() {{
put("hello", new MyObj("hello"));
put("world", new MyObj("world"));
}};
Then you can use:
if (map.containsKey("hello"))
and to get the corresponding object:
MyObj o = map.get("hello"); // get() returns null if key not found
It is not equals of your object called when contains executes but the one from String class.
And String implementation checks with instanceof whether the class is a String to perform String-like operations to determine the answer. If object is not a String it will return false;
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()
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