加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java.lang.Class和相等

发布时间:2020-12-15 02:54:11 所属栏目:Java 来源:网络整理
导读:根据类的 javadoc 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. 但是当我跑下面的时候 int[] intArray = { 1,2 };out.println(intArray.g
根据类的 javadoc

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.

但是当我跑下面的时候

int[] intArray = { 1,2 };
out.println(intArray.getClass().hashCode());
int[] int2Array = { 1,2 };
out.println(int2Array.getClass().hashCode());

out.println(intArray.equals(int2Array));

我得到以下输出

1641745
1641745
false

我想知道为什么equals返回false,即使这两个数组都是int类型并具有相同的维度.

解决方法

这是因为您在数组实例上调用了 equals()而不是它们的Class对象.尝试:
out.println(intArray.getClass().equals(int2Array.getClass())); //prints true

你也可以这样写:

out.println(int[].class.equals(int[].class)); //prints true thankfully

另外,匹配的哈希码并不一定表示相等,尽管这并不重要.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读