I am trying to compare if two boolean values have the same logic value, but the code works only if I compare the same object,for the following code the output will be false and I don't understand why:
public class Logic {
private boolean bo;
public Logic(boolean bo) {
this.bo=bo;
}
public boolean equals(Object obj) {
if (this==obj)
return true;
else
return false;
}
public static void main(String[] args) {
Logic l1,l2;
l1=new Logic(true);
l2=new Logic (true);
System.out.println(l1.equals(l2));
}
}
You are comparing the objects not the attributes in your equals
method. The right way would be:
public boolean equals(Logic obj) {
return this.bo==obj.bo;
}
you can to use this
// compare() method of Boolean class
class GeeksforGeeks {
// Driver method
public static void main(String[] args)
{
// first value
boolean a = true;
// second value
boolean b = true;
// compare method
System.out.println(a + " comparing with " + b
+ " = " + Boolean.compare(a, b));
}
}
or check this link enter link description here
You should not compare Object like that if you need Boxed Object like Ingeter, Boolean and etc. Right approach to do that unbox it, like below:
Boolean b1 =new.., Boolean b2=new...; boolean bb1=b1; boolean bb2=b2; Now compare between bb1 and bb2;
As you know new objects are always created in heap space and the references to these objects are stored in stack memory. When you compare two objects using ==
it checks if their reference are point to the same object or not? It doesn't check objects content. Using your implementation of equal
method (comparing object using ==
), the output of running:
public static void main(String[] args) {
Logic l1, l2, l3;
l1 = new Logic(true);
l2 = new Logic(true);
l3 = l1;
System.out.println(l1.equals(l2));
System.out.println(l1.equals(l3));
}
would be:
false
true
Because l1
and l2
point to different objects but l1
and l3
point to a same object in heap. We should override equals
method so that it compares equality of contents. According to the Java Language Specification, there is a contract between equals(Object) and hashCode():
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.
With these in mind we can override equals(Object obj)
and hashCode()
like this:
@Override
public int hashCode() {
return Boolean.hashCode(bo);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this.getClass() == obj.getClass()) {
return bo == ((Logic) obj).boValue();
}
return false;
}
private boolean boValue() {
return bo;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.