黑马程序员技术交流社区

标题: String类中地址及对象内容之间比较的判断 [打印本页]

作者: lishang    时间: 2015-7-19 23:25
标题: String类中地址及对象内容之间比较的判断
String类中==和equals的区别:

因为java所有类都继承于Object基类,而Object中equals用==来实现,所以equals和==是一样的,都是比较对象地址,java api里的类大部分都重写了equals方法,包括基本数据类型的封装类、String类等。对于String类==用于比较两个String对象的地址,equals则用于比较两个String对象的内容(值)。
  例1:字符串常量池的使用

String s0 = "abc";
String s1 = "abc";
System.out.println(s0==s1); //true  可以看出s0和s1是指向同一个对象的。
  例2:String中==与equals的区别

String s0 =new String ("abc");
String s1 =new String ("abc");
System.out.println(s0==s1); //false 可以看出用new的方式是生成不同的对象
System.out.println(s0.equals(s1)); //true 可以看出equals比较的是两个String对象的内容(值)
    例3:编译期确定  

String s0="helloworld";
String s1="helloworld";
String s2="hello" + "word";
System.out.println( s0==s1 ); //true 可以看出s0跟s1是同一个对象
System.out.println( s0==s2 ); //true 可以看出s0跟s2是同一个对象
分析:因为例子中的 s0和s1中的"helloworld”都是字符串常量,它们在编译期就被确定了,所以s0==s1为true;而"hello”和"world”也都是字符串常量,当一个字符串由多个字符串常量连接而成时,它自己肯定也是字符串常量,所以s2也同样在编译期就被解析为一个字符串常量,所以s2也是常量池中"helloworld”的一个引用。所以我们得出s0==s1==s2;

      例4:编译期无法确定

String s0="helloworld";
String s1=new String("helloworld");
String s2="hello" + new String("world");
System.out.println( s0==s1 ); //false  
System.out.println( s0==s2 ); //false
System.out.println( s1==s2 ); //false
    分析:用new String() 创建的字符串不是常量,不能在编译期就确定,所以new String() 创建的字符串不放入常量池中,它们有自己的地址空间。

s0还是常量池中"helloworld”的引用,s1因为无法在编译期确定,所以是运行时创建的新对象"helloworld”的引用,s2因为有后半部分new String(”world”)所以也无法在编译期确定,所以也是一个新创建对象"helloworld”的引用;

     例5:编译期优化

复制代码
String s0 = "a1";
String s1 = "a" + 1;
System.out.println((s0 == s1)); //result = true  
String s2 = "atrue";
String s3= "a" + "true";
System.out.println((s2 == s3)); //result = true  
String s4 = "a3.4";
String s5 = "a" + 3.4;
System.out.println((a == b)); //result = true
复制代码
    分析:在程序编译期,JVM就将常量字符串的"+"连接优化为连接后的值,拿"a" + 1来说,经编译器优化后在class中就已经是a1。在编译期其字符串常量的值就确定下来,故上面程序最终的结果都为true。

    例6:编译期无法确定

String s0 = "ab";
String s1 = "b";
String s2 = "a" + s1;
System.out.println((s0 == s2)); //result = false
    分析:JVM对于字符串引用,由于在字符串的"+"连接中,有字符串引用存在,而引用的值在程序编译期是无法确定的,即"a" + s1无法被编译器优化,只有在程序运行期来动态分配并将连接后的新地址赋给s2。所以上面程序的结果也就为false。

    例7:编译期确定

String s0 = "ab";
final String s1 = "b";
String s2 = "a" + s1;  
System.out.println((s0 == s2)); //result = true
    分析:和[6]中唯一不同的是s1字符串加了final修饰,对于final修饰的变量,它在编译时被解析为常量值的一个本地拷贝存储到自己的常量 池中或嵌入到它的字节码流中。所以此时的"a" + s1和"a" + "b"效果是一样的。故上面程序的结果为true。

    例8:编译期无法确定

String s0 = "ab";
final String s1 = getS1();
String s2 = "a" + s1;
System.out.println((s0 == s2)); //result = false
private static String getS1() {  return "b";   }
    分析:JVM对于字符串引用s1,它的值在编译期无法确定,只有在程序运行期调用方法后,将方法的返回值和"a"来动态连接并分配地址为s2,故上面 程序的结果为false。
作者: 徐会会    时间: 2015-7-20 08:13
厉害厉害,,
作者: 耀阳圣尊    时间: 2015-7-20 11:24
赞赞
作者: Matrix_heima    时间: 2015-7-20 11:35
超赞
作者: a12366456    时间: 2015-7-20 14:51
写的不错,很有启发
作者: 李文思    时间: 2015-7-20 15:58
赞一个,学到东西了。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2