先看下面的代码
int[] a = new int[10];
int[] b = new int[10];
System.out.println(a==b);
上面代码会直接打印出 false , 正常来讲初始化的int数组值应该都是0 , 那为什么两个数组不相等呢
rootcause在于, 数组并不会重写Object.equals() 方法, 而原始的equals方法比较的是引用
两个数组的引用不同, 自然结果是false
正确的做法应该是使用Arrays.equals(a,b)
import java.util.Arrays;
public class Test {
public static void main(String args[]){
int[] a = new int[10];
int[] b = new int[10];
System.out.println(a[0]);
System.out.println(a==b);
System.out.println(Arrays.equals(a, b));
}
}
