According the javadoc of Class
Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions.
But when I run the below
int[] intArray = { 1, 2 };
out.println(intArray.getClass().hashCode());
int[] int2Array = { 1, 2 };
out.println(int2Array.getClass().hashCode());
out.println(intArray.equals(int2Array));
I get the below output
1641745
1641745
false
I am wondering why the equals is returning false even though both the arrays are of int
type and have the same dimensions.
We can use == operators for reference comparison (address comparison) and . equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects.
Java String equals() Method The equals() method compares two strings, and returns true if the strings are equal, and false if not.
lang Description. Provides classes that are fundamental to the design of the Java programming language. The most important classes are Object , which is the root of the class hierarchy, and Class , instances of which represent classes at run time.
You can check the equality of two Strings in Java using the equals() method. This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
This is because you're calling equals()
on the array instances themselves instead of their Class
object. Try:
out.println(intArray.getClass().equals(int2Array.getClass())); //prints true
You could also write:
out.println(int[].class.equals(int[].class)); //prints true thankfully
As an aside, matching hash codes don't necessarily indicate equality, though that doesn't matter here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With