Can someone explain why, A.equals(B) is false, when I initiate B using int[] B = A.clone() BUT true if I initiate B using int[] B = A?
int[] A = {1, 2, 3, 4, 5};
int[] B = A;
//int[] B = A.clone();
if(A==B){//true
System.out.println("Equal");
}
if(A.equals(B)){//true
System.out.println("Equal");
}
Apparently, equals method for arrays in Java is comparing reference equality (same as ==).
If you clone it, you have a reference different object - the clone array. But, if you just point another reference to it it's the same.
Well if you use
int[] B = A;
then B and A refer to the same object, so trivially they're equal. The first comparison (==) would certainly return false between A and A.clone() as the values refer to different objects. It sounds like arrays don't override equals (e.g. as ArrayList does), hence the clone not being equal to the original under the equals method either.
EDIT: Indeed, from the language specification section 10.7, Array Members:
All the members inherited from class Object; the only method of Object that is not inherited is its clone method.
In other words, the array overrides clone() but not toString / hashCode / equals.
For comparing arrays in Java, you might want to try
java.util.Arrays.equals(a,b);
If you use a == b they should be different- this compares their memory references.
If you use a.equals(b), it probably inherits from Object, which simply uses ==.
That probably explains why they made Arrays.equals() in the first place. Now why they chose a.equals(b) to not compare elements... hard to say.
Your question is answered precisely by the Javadoc for clone():
http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#clone%28%29
specifically:
[ The clone() method ] Creates and
returns a copy of this object. The
precise meaning of "copy" may depend
on the class of the object. The
general intent is that, for any object
x, the expression:
x.clone() != x
will be true, and that the expression:
x.clone().getClass() == x.getClass()
will be true, but these are not
absolute requirements. While it is
typically the case that:
x.clone().equals(x)
will be true, this is not an absolute
requirement.
int[] B = A;
Makes B point to the same object in memory as A, so not only are they equal, they are the same.
when you assign B = A, you assign the reference to the same object. With clone() you get a copy of the object. The equality operator (==) tests if both symbols reference the same object where .equals method checks if the two objects have the same value (defined by the implementation of the class)
Related
on the oracle java documentation,
equals() from list says two lists are defined to be equal if they contain the same elements.
But from object class equals() return true only if their hash code is equal.
It means equals() from list overrides equals method from object class. And it's same for equals() from string. As long as they have same characters, they return true.
so whenever I declare a type as String, or use list classes like arraylist
equals() are overriden automatically righT?
equals() are overridden automatically righT?
Answer : Yes absolutely right, If you are asking overriden .equals() method is invoked automatically at run time
**Object class is parent class for every class in java and it consist of .equals() method which compares the object references
But String class, Wrapper classes (Integer,Long etc..) and Collections Classes (ArrayList, hashSet etc..) are overridden .equals() method to compare content in object instead of object references
to avoid confusions here is the clear example
public class Main2 {
public static void main(String[] args) {
List<String> l1 = new ArrayList<>();
l1.add(new String("hello"));
List<String> l2 = new ArrayList<>();
l2.add(new String("hello"));
System.out.println(l1.equals(l2)); //true
List<Test> t1 = new ArrayList<>();
t1.add(new Test());
List<Test> t2 = new ArrayList<>();
t2.add(new Test());
System.out.println(t1.equals(t2)); //false
}
}
class Test{
}
In the above example comparing List<String> will return true because .euqals() method in String is overridden to compare content
But while comparing Lits<Test> will return false even though both objects are empty, since .equals() method in Test class is not overridden by default it will invoke Object class .equals() method which compares reference of objects as == does
Google Question object class equals method compares hashcode ?
Answer
The java.lang.Object class requires that any two objects that compare equal using the equals() method must produce the same integer result when the hashCode() method is invoked on the objects [API 2014]. The equals() method is used to determine logical equivalence between object instances.Feb 12, 2018
equals() are overriden automatically righT?
No. Methods are not overwritten "automatically".
You can look at the code - both classes have their own implementation of equals and hashCode. This implementation is what is used at runtime. If you're writing your own class, you will likely implement equals and hashCode.
But from object class equals() return true only if their hash code is equal.
I think you (and the original version of the other answer) are misunderstanding the documentation on equals:
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.
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.
The only part of this that refers to hashCode is at the end, which specifies that equal objects must have equal hash codes - this isn't automatic, it's by convention so things like HashMap will work.
Comparing hashCode values is NOT the default implementation of equals, and should NEVER be the implementation of equals - it is possible to have multiple non-equal objects with the same result for hashCode. The rule is to make sure your hashCode implementation returns the same value if objects are equal.
As an example, both of these will output the same hashCode, but are clearly not equal:
System.out.println("Aa".hashCode());
System.out.println("BB".hashCode());
Recommended further reading: this related question.
No, .equals() would not magically get overwritten when String are getting compared in list.
the String Class in java already has the .equals() method overwritten in its definition to compare characters by default.
meaning, even without a list if you do this:
String a = new String("abc");
String b = new String("abc");
System.out.println(a.equals(b));
Then, your output would be true
refer this: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
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
The following code is not creating shallow copy as the Javadoc mentioned about clone() method
// Do the same with object arrays
obj O[] = new obj[5];
obj Oc[] = O.clone();
System.out.println("Identity hashcode of obj arrays");
System.out.println(System.identityHashCode(O));
System.out.println(System.identityHashCode(Oc));
// check objects equalness
if(O.equals(Oc)){
System.out.println("Objects are equal!");
}
Output:
Identity hashcode of obj arrays
2018699554
1311053135
Where am I going wrong?
Yes, the output is as expected. The identity hashcodes of both arrays will be different because they are 2 different Objects (being pointed to by 2 different references) at the top level. So, the if.. condition fails as well.
What shallow copy means is : The container (Array, List etc) will be created but ht elements / references inside them will not be created newly, instead, the original references will be used / copied.
You seem to expect that the cloned array will be equal to the original array, as determined by calling O.equals(Oc).
But since arrays don't override Object.equals (JLS 10.7) this call only tests if O == Oc.
Therefore even if O.equals(Oc) does return false, this does not mean that Oc is not a shallow copy of O.
To test equality of array elements, you can use Arrays.equals(O, Oc)
The clone method will return a reference to a new array, which
references the same objects as the source array
HashCode of both the arrays will not be same, these two are two different objects.
I've noticed that you can't compare 2 points like this:
if (pointOne == pointTwo) { }
I always have to do it like this:
if (pointOne.x == pointTwo.x && pointOne.y == pointTwo.y) { }
I really wonder why you can not use the first example, does anyone have an answer?
You must use the equals method of class Point. Check this.
If you use == what you are actually doing is checking if the memory address of the two Point objects is the same.
In Java, all classes are derived from Object, and you can override the equals method, providing a convenient way of checking if in fact, two objects of the same Object derived class, are the same.
== operator checks both reference pointing to the same object or not.
You should use equals method of Point object -
pointOne.equals(pointTwo);
Determines whether or not two points are equal. Two instances of
Point2D are equal if the values of their x and y member fields,
representing their position in the coordinate space, are the same.
Documentation
Because the Point is reference, and if you need to use equals, you need to override the method equal. Java doest not support override operators like "==".
I assume pointOne and pointTwo are objects of some class? You cannot overload operators in java, that is why you have to compare fields.
In such cases it is a good practive to override the equals method for your class and use it this way:
PointOne.equals(PointTwo)
Well this will be an object comparison. You would be comparing memory locations if you compare using ==.
You could override and call Equals.
You can use your first example because running pointOne.x == pointTwo.x compares the primitive types (int) which the == operator is capable of.
When you run pointOne == pointTwo you're comparing the Point object references, which they're not.
As others have said, you can use pointOne.equals(pointTwo)
What is the difference between identity and equality in OOP (Object Oriented Programming)?
identity: a variable holds the
same instance as another variable.
equality: two distinct objects can
be used interchangeably. they often
have the same id.
Identity
For example:
Integer a = new Integer(1);
Integer b = a;
a is identical to b.
In Java, identity is tested with ==. For example, if( a == b ).
Equality
Integer c = new Integer(1);
Integer d = new Integer(1);
c is equal but not identical to d.
Of course, two identical variables are always equal.
In Java, equality is defined by the equals method. Keep in mind, if you implement equals you must also implement hashCode.
Identity determines whether two objects share the same memory address. Equality determines if two object contain the same state.
If two object are identical then they are also equal but just because two objects are equal dies not mean that they share the same memory address.
There is a special case for Strings but that is off topic and you'll need to ask someone else about how that works exactly ;-)
Identity means it is the same object instance while equality means the objects you compare are to different instances of an object but happen to contain the same data.
Illustration (in java)
Date a = new Date(123);
Date b = new Date(123);
System.out.println(a==b); //false
System.out.println(a.equals(b)); //true
So a and b are different instances (different allocations in memory) but on the "data" level they are equal.
For instance,
In StackOverFlow:
identity: I am Michael, you are
sevugarajan, so we are not same.
equality: if we have same reputation
scores, we are equal in some ways.
In Java and similar languages which 'leak' the abstraction of a reference of an object, you can test whether two references refer to the same object. If they refer to the same object, then the references are identical. In Java, this is the == operator.
There is also an equals method which is used to test whether two objects have the same value, for example when used as keys of a HashSet (the hash code of equal objects should also be equal). Equal objects should have the same 'value' and semantics when used by client code.
Purer object-oriented languages do not have an identity comparison, as client code generally shouldn't care whether or not two objects have the same memory address. If objects represent the same real-world entity, then that is better modelled using some ID or key value rather than identity, which then becomes part of the equals contract. Not relying on the memory address of the object to represent real-world identity simplifies caching and distributed behaviour, and suppressing == would remove a host of bugs in string comparison or some uses of boxing of primitives in Java.
Think about the words "identical" and "equivalent". If two things are identical, they have the same identity; they are same thing. If they are equivalent, one can be substituted for the other without affecting the outcome; they have the same behavior and properties.
Identity: Two references to the same object (o1 == o2).
Equality: The method o1.equals( o2 ) returns true. This doesn't necessarily mean that the two objects contain (all) the same data.
In theory it's possible to override a method equals() to return false even for identical objects. But this would break the specification 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.
Identity concept is quite philosophical, that's why you shouldn't reconduce it just to references.
You can say that two identities are the same if a change to the first is reflected on the second and vice-versa. Of course this includes also sharing the same memory address but in general while identity is related to the attributes of the object, equality is used to check whenever two objects are identical, but this doesn't include identity.
The viceversa is quite obvious, if two items have the same identity they are also equal (in equality terms of being interchangeable).
For primitive types ( int , boolean , char, long , float ... )
== and != is equality test
and for Objects
== and != is identity test. [ it compares only the reference ]
equals method is used for equality test of Objects [ it can be overridden to compare specific attributes]
i found an excellent article on this
http://www.cs.cornell.edu/courses/cs211/2006sp/Lectures/L14-Comparison/L14cs211sp06.pdf
http://ocw.mit.edu/NR/rdonlyres/Electrical-Engineering-and-Computer-Science/6-170Fall-2005/D659DC53-FB1D-403C-8E35-2CAECBED266E/0/lec12.pdf
Quote
I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as equals. :D
Sir Winston Churchill
x == y is true only if there's the same object referenced by variables x and y.
x.equals(y) depends on the implementation of x.equals(), and is usually less strict that the above, as it compares the content of the object. (In Java, if x.equals(y), it must also be true that x.hashCode() == y.hashCode();)
Example:
Integer w = new Integer(3);
Integer x = new Integer(1);
Integer y = x;
Integer z = new Integer(1);
// all of these evaluate to true
y.equals(x) // it's the same object, of course the content is same
x.equals(z) // different objects, same content (`1`)
z.equals(y)
!w.equals(x); // the content is different (`3` vs `1`)
!w.equals(y);
!w.equals(z);
x == y // same object
z != x // different objects
y != z
w != x
Identical vs. Equal objects
Two objects are said to have identical states (deep equality) if the graphs representing their states are identical in every respect, including the OIDs at every level.
Two objects are said to have equal states (shallow equality) if the graphs representing their states are same, including all the corresponding atomic values. However, some corresponding internal nodes in the two graphs may have objects with different OIDs.
Example: This example illustrates the difference between the two definitions for comparing object
states for equality.
o2 = (i 2 , tuple, <a 1 :i 5 , a 2 :i 6 >)
o3 = (i 3 , tuple, <a 1 :i 4 , a 2 :i 6 >)
o4 = (i 4 , atom, 10)
o5 = (i 5 , atom, 10)
o6 = (i 6 , atom, 20)
In this example, the objects o1 and o2 have equal states (shallow equality), since their states at the atomic level are the same but the values are reached through distinct objects o 4 and o 5 .
However, the objects o1 and o3 have identical states (deep equality), even though the objects themselves are not because they have distinct OIDs. Similarly, although the states of o4 and o5 are identical, the actual objects o4 and o5 are equal but not identical, because they have distinct OIDs.
To add, identity is also known as referential check (references to objects, get it?) and equality as structural check by some authors. At the end of the day an object in memory abstract is just a map/table structure indexed at certain memory address. There can be one or many references (memory addresses) pointing to it. They all are referential-ly identical. When contents of same object is copied to another counterpart then both are structurally equal.