public class TestEquals{

public static void main(String[] args){

Integer a = new Integer(128);
Integer b = new Integer(128);
System.out.println(a == b);
System.out.println(a.equals(b));

Test t1 = new Test();
Test t2 = new Test();
System.out.println(t1 ==t2 );
System.out.println(t1.equals(t2));
}

}
为什么输出false,true,false,false
其中Test类没覆盖equals()方法也就是继承了Object类的equals()方法

解决方案 »

  1.   

    Test类继承了Object类的equalse()方法,而Object类的equales()方法是这么写的:
    public boolean equals(Object obj) {
        return (this == obj);
    }
    所以就返回false了。
    而Integer类则Override了Object的equalse()方法:
    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }
    所以就返回true了呗!
      

  2.   

    谢谢了,之前以为Integer类也是直接继承了Object类的equals()方法,没重写,原来重写了
      

  3.   

    Integer中的源码 /**
         * Compares this object to the specified object.  The result is
         * <code>true</code> if and only if the argument is not
         * <code>null</code> and is an <code>Integer</code> object that
         * contains the same <code>int</code> value as this object.
         *
         * @param   obj   the object to compare with.
         * @return  <code>true</code> if the objects are the same;
         *          <code>false</code> otherwise.
         */
        public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
        }
    楼主应该知道为什么Integer的equal是true了吧