JAVA中equals()方法的重要性

对于对象比较使用equals()方法的重要性,这里以String类为例进行了比较。

/**
 * 对于对象比较使用equals()方法的重要性,这里以String类为例进行了比较。
 * @author HAN
 *
 */
public class TestEqual {
	public TestEqual(){
		testMethod();
	}
	void testMethod(){
		String str=new String("Gaowen HAN");
		String str2=new String("Gaowen HAN");
		String str3="Gaowen HAN";
		String str4="Gaowen HAN";

		if(str.equals(str2)){
			System.out.println("str is equal to str2");
		}else{
			System.out.println("str is not equal to str2");
		}
		
		if(str3==str4){
			System.out.println("str is equal to str2");
		}else{
			System.out.println("str is not equal to str2");
		}
		
		if(str==str2){
			System.out.println("str is equal to str2");
		}else{
			System.out.println("str is not equal to str2");
		}
		
		if(str.equals(str3)){
			System.out.println("str is equal to str2");
		}else{
			System.out.println("str is not equal to str2");
		}
			
		if(str==str3){
			System.out.println("str is equal to str2");
		}else{
			System.out.println("str is not equal to str2");
		}
		
	}
	public static void main(String[] args) {
		new TestEqual();
	}
}		


posted on 2011-12-29 20:55  java课程设计例子  阅读(195)  评论(0编辑  收藏  举报