我有以下測試程序。我創建了3 Integer
引用。我創建了2 Integer
對象,並使引用i1和i2分別引用它們。我把參考i3等於i1。現在i1等於()i3應該顯然是正確的,因爲它們都指向堆上的同一個對象。但爲什麼i1應該等於()到i2?他們指的是兩個不同的對象。我錯過了什麼。java的equals()方法
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");
}
}
equals是您可以讀取源的方法。看看Integer.equals(),那會回答你的問題。 – 2009-12-31 19:57:16