转java string 比较

本文详细解析了 Java 中 String 类型的创建、比较、互操作性等关键特性,包括 String 对象在堆和常量池中的存储方式,== 和 equals 方法的区别,intern() 方法的作用,以及如何通过字符串数组和 char 数组进行字符串操作。同时,通过实例代码展示了如何在实际编程中灵活运用这些特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. String s = new String("abc");

在编译期,根据“abc”创建一个对象,存放到string pool中,这时需要查看string pool中是否已经有了“abc”,若已有则不创建,若无则创建。

在运行期,根据new创建一个对象,存放到heap中。即将pool中的对象复制一份到heap中,并把heap中的这个对象引用交给s持有。

综上,该语句创建一个或两个对象。 导致在heap中出现内容相同而地址不同的String对象。

 

2. String s1 = "abc";

在编译期,根据“abc”创建一个对象,存放到string pool中,这时需要查看string pool中是否已经有了“abc”,若已有则不创建,若无则创建。

 

3. ==是比较地址,equals是比较内容 。

 

4. intern()方法:查找内容相同的字符串,如:

String s2 = "hello";//hello不存在,创建新对象存在string pool中(1) String s2 = new String("hello");//创建新对象存在heap中 s1 == s2;//false 地址不同 s1.equals(s2);//true 内容相同 s2 = s2.intern();//查找与s2内容相同的对象,并赋给s2 s1 == s2;//true 此时s1,s2同指向(1)  

 

5. java中所有的字符串文字都是一个String对象

 

6. String是不可变类,线程安全,不存在任何修改对象的方法

 

7. StringBuffer是可变类,用来修改对象

StringBuffer D = new StringBuffer("ss");//创建两个对象

D.append("test");//在new对象上直接处理,不产生新的对象

 

实例

Java代码 复制代码  收藏代码
  1. public class StringChar {   
  2.     public static void main(String[] args){   
  3.         String s = "hello";//(1)存放在Constant pool里的String pool里   
  4.         String s2 = new String("hello");//(2)new出来的对象存放在heap里   
  5.         String t = "hello";//(3)因为string pool里已经有了hello,所以t与s指向同一内存地址   
  6.         String str = "hello";//(4)同上   
  7.         char c[] = {'h','e','l','l','o'};   
  8.            
  9.         char ch[] = str.toCharArray();//string转换为char   
  10.            
  11.         if(ch == c){   
  12.             System.out.println("true");   
  13.         }else{   
  14.             System.out.println("flase");   
  15.         }//false   
  16.            
  17.         if(ch.equals(c)){   
  18.             System.out.println("true");   
  19.         }else{   
  20.             System.out.println("flase");   
  21.         }//false why???   
  22.            
  23.         if(s2 == s){//"=="判断引用是否相同,即是否指向同一内存地址   
  24.             System.out.println("true");   
  25.         }else{   
  26.             System.out.println("flase");   
  27.         }//false   
  28.            
  29.         if(s2.equals(s)){//equals()判断两个object是否一样,即所有的成员值都相同   
  30.             System.out.println("true");   
  31.         }else{   
  32.             System.out.println("flase");   
  33.         }//true   
  34.            
  35.         s2 = s2.intern();//intern()找到与s2内容相同的对象,并将其赋给s2   
  36.         System.out.println(s == s2);//true 此时s2和s指向同一对象(1)   
  37.         System.out.println(t == s2);//true 因为t和s指向同一对象(1),所以此时t和s2指向同一对象(1)   
  38.         System.out.println(str == s2);//true 同上   
  39.     }   
  40.   
  41. }   
  42.    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值