java的equals()方法

gam*_*ver 1 java class

我有以下测试程序.我创建了3个Integer引用.我创建2个Integer对象并使引用i1和i2分别引用它们.我让i3等于i1.现在i1 equals()i3显然应该是真的,因为它们都引用堆上的相同对象.但为什么i1应该与i2相等?他们指的是两个不同的对象.我错过了什么

文件说:

public boolean equals(Object obj)
     Indicates whether some other object is "equal to" this one.


public class Test{

    public static void main(String [] args)
    {
        Integer i1 = new Integer(10);
        Integer i2 = new Integer(10);
        Integer i3 = i1;

        if(i1.equals(i3)) // UNDERSTANDABLE
            System.out.println("equal");

        if(i1.equals(i2)) // prints equal. WHY !!!!!
            System.out.println("equal");    
}

}
Run Code Online (Sandbox Code Playgroud)

Fab*_*eeg 12

equals()包装类型的方法测试值相等,如果要测试引用相等,请==改用,例如

System.out.println(new Integer(1) == new Integer(1));
Run Code Online (Sandbox Code Playgroud)


Cla*_*diu 5

equals是相等的价值版本.类重写此方法以定义值相等意味着什么.例如,要查看两个字符串是否包含相同的字符序列,请使用该.equals()方法.如果要创建自己的类,例如,要将其添加到a HashMap,则必须同时定义a hashCode()equals()方法才能使其正常工作.

要查看两个引用是否指向相同的内存位置,请使用==.