== 与equals的用法

                       == 与equals的用法

== 的用法   ==比较对象在内存中的地址是否相等。

equals的用法    equals比较的是对象之间内容是否相同。

 

代码
public class StringTest {
public static void main(String[] args) {
String str1
= new String("abc");
String str2
= new String("abc");

if(str1 == str2) { // 比较地址是否相等。
System.out.println("str1 == str2");
}
else {
System.out.println(
"str1 != str2");
}

if(str1.equals(str2)) { // 比较内容是否相等。
System.out.println("str1 is equals str2");
}
else {
System.out.println(
"str1 is not equals str2");
}
}
}
/*
output:
str1 != str2
str1 is equals str2
*/

 

equals方法是Object类中定义的。

public boolean equals(Object obj) {
return (this == obj);
}

如果在其它类中想要使用它而达到某种目的,那么你需要重写它,然后编写一些目的代码。比如这里的String类就是重写了equals方法。

 

equals(Object) 方法是 Object 类中定义的方法。该方法是直接使用 “==” 比较的两个对象,所以在没有覆盖 equals(Object) 方法的情况下,equals(Object) 与 “==” 一样是比较的引用。equals方法的实质仍然是用==比较两个对象。

equals(Object) 方法与 “==” 相比的特殊之处就在于它可以覆盖(重写),所以我们可以通过覆盖的办法让它不是比较引用而是比较数据内容

代码
String s0 = "hello";
String s1
= "hello";
String s2
= "he" + "llo";
String s3
= new String("hello");
String s4
= "he";
String s5
= "llo";
String s6
= s4 + s5;
System.out.println(s0
== s1); // ?
System.out.println(s0 == s2); // ?
System.out.println(s0 == s3); // ?
System.out.println(s0.equals(s3)); // ?
System.out.println(s0 == s6);// ?
System.out.println(s0.equals(s6));// ?
/*

* output: true true false true false true
*/

 

posted @ 2010-12-22 09:44  meng72ndsc  阅读(323)  评论(0编辑  收藏  举报