对于这个程序,为什么class A中的equals方法回对结果产生影响?
它和Arrays.equals有重载关系?想不明白。
我并没调用它啊?
谢谢各位大虾!!!import java.util.Arrays;//用于创建数组对象的数组
class A {
protected int x;
A(int x) { this.x = x; }
//新添加的方法,证明数组元素相同
public boolean equals(Object b) {
return (this.x == ((A)b).x) ? true : false;
}
}public class EqualTest {
public static void main(String[] args) {
//创建两个数组
A[] a1 = { new A(1), new A(2), new A(3) };
A[] a2 = { new A(1), new A(2), new A(3) };
//输出结果
System.out.println(Arrays.toString(a1));
System.out.println(Arrays.toString(a2));
System.out.println(Arrays.equals(a1, a2));
}
}

解决方案 »

  1.   

    是Arrays.equals会调用a1,a2的类中定义的equals方法,如果你没有定义,就会调用Object类的equals方法
      

  2.   

    Arrays.equals(a1, a2)会对数组的每一位进行 == 或者 eqauls 比较,你又重写了自定义对象的equals方法。    public static boolean equals(Object[] a, Object[] a2) {
            if (a==a2)
                return true;
            if (a==null || a2==null)
                return false;        int length = a.length;
            if (a2.length != length)
                return false;        for (int i=0; i<length; i++) {
                Object o1 = a[i];
                Object o2 = a2[i];
                if (!(o1==null ? o2==null : o1.equals(o2)))
                    return false;
            }        return true;
        }
      

  3.   

    Returns true if the two specified arrays of Objects are equal to one another. The two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.Documentation里Arrays的equal方法的说明
      

  4.   

    结果是这个,又问题吗?
    [A@de6ced, A@c17164, A@1fb8ee3]
    [A@61de33, A@14318bb, A@ca0b6]
    true