首先看下面的小实验:
public class Equals {
public static void main(String[] args) {
int i = 10;
int j = 10;
System.out.println(j == i);
double di = 10;
double dj = 10;
System.out.println(di == dj);
Integer integer1 = new Integer(11);
Integer integer2 = new Integer(11);
System.out.println(integer1 == integer2);
Double doublei = new Double(13);
Double doublej = new Double(13);
System.out.println(doublei == doublej);
String str = new String("hello");
String str1 = new String("hello");
System.out.println(str==str1);
System.out.println(str.equals(str1));
/**
* 根据上面的实验,说明==对于基本类型比较的是值,对于引用类型比较的是引用
*/
int ei = 10;
int ej = 10;
//System.out.println(ei.equals(ej));
Float ef1 = new Float(100);
Float ef2 = new Float(100);
System.out.println(ef1.equals(ef2));
Pet pet1 = new Pet();
Pet pet2 = new Pet();
System.out.println(pet1.equals(pet2));
/**
* 根据上面的实验,说明equals对于基本类型不可用,对于引用类型比较的是引用。然而诸如String、Date、Float、Integer等类对equals方法进行了重写的话,比较的是所指向的对象的内容。
*/
}
}
class Pet{}
分析:
我们来看一下String类的equals的源码:
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
所以,以后遇到非基本类型比较对象是否是同一对象使用“==”。使用equals()方法对于重写了该方法的一些类则是比较的值是否相等,不然还是比较的对象。