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");
Related
I want to store data in a map, with key unicity, but I would like the map to use the equals method of my key class.
It seems that HashMap doesn't use the equals method (I may be wrong, if so my tests are wrong).
My problem here is that the map use hashCode to check for duplicate, and I would like a map implementation that use equals.
I am storing timestamp in the key, and would like to make it so that 2 keys are equals if there timestamp difference does not exceed a defined amount (let say 1000 ms).
Edit : code
public class CleanKey
{
private DateTime start;
private DateTime end;
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((end == null) ? 0 : end.hashCode());
result = prime * result + ((start == null) ? 0 : start.hashCode());
return result;
}
public boolean equals(Object obj)
{
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
CleanKey other = (CleanKey) obj;
if(end == null)
{
if(other.end != null)
return false;
}
else if(Math.abs(Millis.millisBetween(end, other.end).getMillis()) > 1000)
return false;
if(start == null)
{
if(other.start != null)
return false;
}
else if(Math.abs(Millis.millisBetween(start, other.start).getMillis()) > 1000)
return false;
return true;
}
}
It seems that HashMap doesn't use the equals method (I may be wrong, if so my tests are wrong).
It does use equals, but it uses hashCode first. It will only bother calling equals on keys with the same hash code - that's how it manages to be efficient. That's not a problem so long as your hashCode and equals method obey the contract specified in java.lang.Object.
I am storing timestamp in the key, and would like to make it so that 2 keys are equals if there timestamp difference does not exceed a defined amount (let say 1000 ms).
You can't do that. It violates the contract of equals, because you can't have transitivity. Suppose we have three keys x, y, and z with the following timestamps:
x 400
y 1200
z 2000
By your description, x.equals(y) would be true, y.equals(z) would be true, but x.equals(z) would be false, thus violating the contract of Object.equals.
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.
You need to override hashCode and equals in you class.
Here: Understanding the workings of equals and hashCode in a HashMap
Edit after seeing the code :
Hashcode is returning wrong value because you are using end field to calculate the hash... different end lead to different hash.
Just for a try... return a constant and the hashmap will work
StringBuffer str1=new StringBuffer("hello1");
StringBuffer str2=new StringBuffer("hello1");
System.out.println(str1.equals(str2));
It will Showing False result Why?
StringBuffer equals() method isn't overridden to check content. It's using the default "shallow equals" that compares references it inherits from java.lang.Object.
So
StringBuffer str1=new StringBuffer("hello1");
StringBuffer str2=new StringBuffer("hello1");
System.out.println(str1.equals(str2));
is Comparing reference that is why you are getting false
There is no overriding of equals in the StringBuffer class. So it inherits the definition from Object class. And from Java API we know its behavior:
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).
You have two different objects, so equals return false in this case.
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.
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()