對於對象比較使用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();
- }
- }