java.lang中String"="和"equals()"函数解析
java.lang是java语言的基础包。String类为lang包中的一个基础类。本文主要讨论 "="和"equals()"方法对String的不同判断结果。
"=" .VS. "equals()" :
"="判断的是两个String类型的引用是否指向同一个对象,如果是,那么表达式结果为true,如果不是,那么表达式结果为false;
"equals"判断的是两个String类型的引用所指向对象的值,如果相等,那么返回结果为true,如果不相等,那么返回结果为false;
下面是我的一段简单的实验程序。
1 package BasicKnowledge.Testlang; 2 3 public class StringTest { 4 public static void main(String args[]) 5 { 6 String str1; 7 str1 = new String("Str"); 8 String str2 = new String("Str"); 9 10 11 12 String str3; 13 str3 = str1; 14 String equal = "The two strings are equal with"; 15 String notEqual = "The two strings are not equal"; 16 17 String stat2 = "str1 and str2 are two different objects but they have the same value"; 18 if(equalSign(str1,str2)) 19 { 20 System.out.println(stat2+";"+equal+" '=' sign"); 21 }else System.out.println(stat2+";"+notEqual+" '=' sign"); 22 23 if(equalFunction(str1,str2)) 24 { 25 System.out.println(stat2+";"+equal+ " 'equal()' function"); 26 }else System.out.println(stat2+";"+notEqual+" 'equal()' fuction"); 27 28 str3 = str1; 29 String stat = "str3 shares the same reference with str1"; 30 31 if(equalSign(str1,str3)) 32 { 33 System.out.println(stat+";"+equal+" '=' sign"); 34 }else System.out.println(stat+";"+notEqual+" '=' sign"); 35 36 if(equalFunction(str1,str3)) 37 { 38 System.out.println(stat+";"+equal+ " 'equal()' function"); 39 }else System.out.println(stat+";"+notEqual+" 'equal()' fuction"); 40 } 41 42 static boolean equalSign(String a, String b)//在静态方法中,是不能访问非静态成员,所以这里用static来形容 43 { 44 boolean backValue = true; 45 if(a == b) 46 { 47 backValue = true; 48 }else backValue = false; 49 return backValue; 50 } 51 52 static boolean equalFunction(String a, String b) 53 { 54 boolean backValue = true; 55 if(a.equals(b)) 56 { 57 backValue = true; 58 }else backValue = false; 59 return backValue; 60 } 61 62 }
编译和运行结果如下:
str1 and str2 are two different objects but they have the same value;The two strings are not equal '=' sign
str1 and str2 are two different objects but they have the same value;The two strings are equal with 'equal()' function
str3 shares the same reference with str1;The two strings are equal with '=' sign
str3 shares the same reference with str1;The two strings are equal with 'equal()' function