在比较对象时候,常常用到 "==" 和 "equals(Object)"。它们常常让初学者感到疑惑。偶曾经初学java时也常常犯这种低级错误,下面给大家一个例子(偶不多作解释了超简单奥!)
[code]import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
public class EqualsDemo {
public static void main(String[] args) {
String s1 = new String("abc");
String s2 = new String("abc");
String s3 = "abc";
String s4 = s3;
String s5 = new String();
try {
/*
* 用beanutil克隆一个对象
*/
BeanUtils.copyProperties(s5, s3);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("用 == 比较结果");
System.out.println(s1 == s2);// false
System.out.println(s1 == s3);
System.out.println(s4 == s3);
System.out.println(s4 == s5);
System.out.println("用equals(Object) 比较结果");
System.out.println(s1.equals(s2));// true
}
}[/code]
[code]import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
public class EqualsDemo {
public static void main(String[] args) {
String s1 = new String("abc");
String s2 = new String("abc");
String s3 = "abc";
String s4 = s3;
String s5 = new String();
try {
/*
* 用beanutil克隆一个对象
*/
BeanUtils.copyProperties(s5, s3);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("用 == 比较结果");
System.out.println(s1 == s2);// false
System.out.println(s1 == s3);
System.out.println(s4 == s3);
System.out.println(s4 == s5);
System.out.println("用equals(Object) 比较结果");
System.out.println(s1.equals(s2));// true
}
}[/code]