Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.Class and equality

Tags:

java

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.

like image 891
Aravind Yarram Avatar asked Dec 12 '11 19:12

Aravind Yarram


People also ask

Why use .equals instead of == Java?

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.

What is equality in Java?

Java String equals() Method The equals() method compares two strings, and returns true if the strings are equal, and false if not.

What is Lang class in Java?

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.

How do you test for equality in Java?

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.


1 Answers

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.

like image 98
Paul Bellora Avatar answered Oct 09 '22 17:10

Paul Bellora