Comparing integer Arrays in Java. Why does not == work?(比较 Java 中的整数数组.为什么 == 不起作用?)
问题描述
我正在学习 Java,只是想出了一个关于该语言的微妙事实:如果我声明两个具有相同元素的整数数组并使用 ==
比较它们,结果是 false代码>.为什么会这样?比较不应该评估为
true
吗?
I'm learning Java and just came up with this subtle fact about the language: if I declare two integer Arrays with the same elements and compare them using ==
the result is false
. Why does this happen? Should not the comparison evaluate to true
?
public class Why {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a == b);
}
}
提前致谢!
推荐答案
使用Arrays.equals(arr1, arr2) 方法.
Use Arrays.equals(arr1, arr2) method.
==
运算符 只是检查两个引用是否指向同一个对象.
The ==
operator just checks if two references point to the same object.
测试:
int[] a = {1, 2, 3};
int[] b = a;
System.out.println(a == b); // returns true as b and a refer to the same array
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(Arrays.equals(a, b)); //returns true as a and b are meaningfully equal
这篇关于比较 Java 中的整数数组.为什么 == 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较 Java 中的整数数组.为什么 == 不起作用?


- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 转换 ldap 日期 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01