比如:
public class TestEquals {
public static void main(String[] args)
{
int a = 3;
int b = 4;
int c = 3;
System.out.println(a == b);//结果是false
System.out.println(a == c);//结果是true
System.out.println(a.equals(c));//错误,编译不能通过,equals方法
//不能运用与基本类型的比较
}
}
(2) 对于基本类型的包装类型,比如Boolean、Character、Byte、Shot、Integer、Long、Float、Double等的引用变量,==是比较地址的,而equals是比较内容的。比如:
public class TestEquals {
public static void main(String[] args)
{ Integer n1 = new Integer(30);
Integer n2 = new Integer(30);
Integer n3 = new Integer(31);
System.out.println(n1 == n2);//结果是false 两个不同的Integer对象,故其地址不同,
System.out.println(n1 == n3);//那么不管是new Integer(30)还是new Integer(31) 结果都显示false
System.out.println(n1.equals(n2));//结果是true 根据jdk文档中的说明,n1与n2指向的对象中的内容是相等的,都是30,故equals比较后结果是true
System.out.println(n1.equals(n3));//结果是false 因对象内容不一样,一个是30一个是31
}
} 作者: 王冬 时间: 2012-7-18 17:05
equals比较的是内容,==比较的是内存地址。作者: 杨正 时间: 2012-7-18 17:54 本帖最后由 杨正 于 2012-7-18 17:57 编辑