This question already has answers here:
equals vs Arrays.equals in Java
(9 answers)
Closed 7 years ago.
I have run this small program:
String[] a = {"a","b"};
String[] b = {"a","b"};
if (a.equals(b)){
System.out.println("woop");
}else{
System.out.println("doh!");
}
if (Arrays.equals(a, b)){
System.out.println("woop");
}else{
System.out.println("doh!");
}
The output of the program is "doh! woop".
I get the difference between the == and .equals but what is the difference between these equals operations?
TL;DR
equals compares array instances, Arrays.equals compares array elements.
Full Explanation
Arrays do not implement equals. As a result, they hand the method off to Object which is implemented as follows.
public boolean equals(Object obj) {
return (this == obj);
}
Thus, equals on an array is the same as ==.
Arrays.equals has the following description. It compares the elements of the array.
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.
Arrays.equals(Object[] a, Object[] a2)...
returns true if the two specified arrays of Objects are equal to one another. The two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. Two objects e1 and e2 are considered equal if (e1==null ? e2==null : e1.equals(e2)). In other words, the two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.
In short, all your Strings are compared through equals.
See API.
Object.equals, which is invoked when comparing two arrays with the array1.equals(array2) idiom, compares the reference, just like ==.
See source for java.lang.Object:
public boolean equals (Object o) {
return this == o;
}
The difference is that a.equals(b) will use == under the hood, since arrays don't override the Object.equals() method. You use this to test for instance equality between arrays.
So in your case, a.equals(b) will return false, since the two arrays are different instances.
Instead, Arrays.equals() actually compares what's inside the arrays. If the arrays contain the same values, then Arrays.equals() returns true. You use this to test for semantic equality between arrays.
With arrays, a.equals(b) is the same as a == b. This is checking if the two array instances are the same. Arrays.equals(a,b) takes the time to compare each element of both arrays and checks if the elements are equal, which is different than checking if the containers themselves are equal.
A quick analogy: Let's say a and b are buckets. Asking if the two buckets are the same is not the same as asking if what is in the buckets is the same.
Related
The question is about static methods Objects.deepEquals class (since Java 7):
public static boolean deepEquals(Object a, Object b) {
if (a == b)
return true;
else if (a == null || b == null)
return false;
else
return Arrays.deepEquals0(a, b);
}
As it said in javadoc of this method:
Returns true if the arguments are deeply equal to each other and false
otherwise.
What I do not understand: where is the depth of comparison? As we can see inside its implementation it just does references comparison, and inside Arrays.deepEquals0(a, b) for simple Object and Object arguments it invokes
just: eq = e1.equals(e2);. So in what kind of sense two objects are deeply equal?
The comparison would be deep, if you passed Array objects.
Non-array objects will not be evaluated deeper than what you get with equals .
So the depth isn't relevant in your case :
Two null values are deeply equal. If both arguments are arrays, the
algorithm in Arrays.deepEquals is used to determine equality.
Otherwise, equality is determined by using the equals method of the
first argument.
Quoted from :
Object.deepEquals
You can refer: Your's Deeply - Why Arrays.deepEquals When We Have Arrays.equals
Arrays.deepEquals looks really deep
From the source, we could understand that Arrays.deepEquals
Loops through the input arrays, gets each pair
Analyses the type of each pair
Delegates the equal deciding logic to one of the overloaded
Arrays.equals if they are one of the primitive arrays
Delegates recursively to Arrays.deepEquals if it is an Object array
Calls the respective object’s equals, for any other object
I found an answer for junit, but need a solution for testng. Any ideas more usefull as writing an own for loop?
There's no need for a separate method for List comparison. Two lists can be compared by org.testng.Assert#assertEquals(Object, Object).
If two lists a and b are non-null, the call Assert.assertEquals(a, b) means a.equals(b) will be called subsequently.
And java.util.List#equals is what you need, as described in javadoc:
Compares the specified object with this list for equality. Returns
true if and only if the specified object is also a list, both lists
have the same size, and all corresponding pairs of elements in the two
lists are equal. (Two elements e1 and e2 are equal if (e1==null ?
e2==null : e1.equals(e2)).) In other words, two lists are defined to
be equal if they contain the same elements in the same order. This
definition ensures that the equals method works properly across
different implementations of the List interface.
I have a written a class like
public class HashCodeImpl{
public int hashCode(){
return 1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
HashCodeUtil h= new HashCodeUtil();
HashCodeUtil h1= new HashCodeUtil();
System.out.println(h.hashCode());
System.out.println(h1.hashCode());
System.out.println(h);
System.out.println(h1);
System.out.println(h==h1);
}
}
OutPut:
1
com.manu.test.HashCodeUtil#1
com.manu.test.HashCodeUtil#1 false
My question is: when my hashCode method is returning same value then why
System.out.println(h==h1);
is coming false?
Please explain.
Because they are two different object references. == compare the references, not the hashCode results.
To get a desired result, you may override the equals method in your class and use h1.equals(h2) to see if they're equivalent. Here you may use the result of hashCode to ease the evaluation of the equality of the objects being compared (this doesn't mean that two objects with the same hash code are equals).
But note that even if the objects have the same hashCode and are equivalent by the definition of the equals method, they are different references that occupy a different place in the heap.
As #ZouZou points out, hashCode equality does not equate to object equality. Having said that, you are not even comparing for object equality. Comparing two objects with == is a reference equality check, which you should almost never use, unless you really know what you're doing.
You're misunderstanding the purpose of the hashCode. As others have pointed out, == compares references and not hash codes. However, an overriding equals method, which compares values and not references, still wouldn't compare hash codes.
Think about it ... A hash code is an int, and therefore there are only 232 possible values for a hash code. But how many possible Strings are there? Many, many more than 232. (Since each char has 216 possible values, there are 248 possible Strings of length three, and the number just keeps growing the longer the Strings get.) Therefore, it is impossible to set up a scheme where two Strings are always equal if their hash codes are equal. The same is true of most other objects (although a class with a relatively small number of possible values could be set up with a unique hash code for each value).
The hashCode's purpose is to come up with a number that can be used for a hashMap or hashSet. We often try to come up with a function that will reduce that chance that unequal objects have unequal hash codes, in order to improve the efficiency of the map or set. But for most objects, of course, it's impossible to guarantee this.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference Between Equals and ==
in which cases equals() works exactly like == operator?
It seems that they both act similar for primitive data types. Are there any other cases in which both of them act equal?
== compares the bits of reference for Object type so if you have reference to same Object it would be the case
For example
Integer for value -128 and 127 (inclusive) it caches (while autoboxing) the instance so it would be the case here for the mentioned range of value of Integer
For primitive data types, there is no equals() (because they are not objects, and have no methods).
The default implementation (in class Object) for equals() just does object identity check (i.e. the same as ==). So if a class does not override it, it will have the same result as ==.
The operator == will always compare references for objects, and the actual value for primitive types.
Note that an array of primitives like int[] is still an object!
String test1 ="test";
String test2 = test1;
System.out.println(test1 == test2);
System.out.println(test1.equals(test2));
Both will print -
true
true
In addition to primitives (which are a special case) == and equals() behave similarly for every case in which reference equality is the same as actual equality:
Interned Strings
Certain Integer references (normally between -128 and +127, but this is configurable, and it depends on how the instance was constructed)
Singletons
Instances of Object (and any other class that doesn't override equals())
Obviously, when in doubt, use equals()
The equals() method evaluates on hashCode comparisons. While == compares objects by reference.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Equals method for objects
i have below code.
public class SomeClass{
OtherClass clas = new OtherClass();
OtherClass some;
some=this;
if(some != this) {
s.y.s.o("true");
}
my question is which one is correct?
some != this or some.equals(this) ?
To compare object references, you use == and !=, while equals is used to compare the values.
What do you want to compare?
== compares to see if the two references are to the EXACT SAME OBJECT.
equals compares to see if the two references are to objects which have matching properties, based on the class-specific criteria in the class's equals implementation.
You use operator!= or operator== when you want to check for identity of two objects [if they are actually the same object]
You use equals() when you want to check for equality. [if two object are equal, as the equals() method defined them].
It is hard to know what exactly you are trying to achieve, but usually when comparing two reference objects, we want to use equals().
In Java == compares references (i.e. addresses) while equals compares object equality (and you can override it to compare based the member variables you see fit)
In your post you compare to see if some is the same object as this. Is this what you want to do? If yes then the some!=this is correct (and is false since some refers to this)
== compares the references. That is, are these two objects located at the same place.
.Equals compares the things pointed to by those references. That is, are these two objects equivalent.