【Java】探究字符串比较值相等时到底为什么要使用equals()而不是==

一、公知结论

1、 ==针对基本类型的数据,比较的是值;对于引用类型则比较内存地址(hashcode)
2、equals方法,对于String类型的数据,因为String重写了此方法,比较的是值(byte[] value)


二、字符串比较测试实验

1、针对同一字符串,==和equals没有区别

 
 //这里简化比较,即平常我们以字面量方式声明的变量
 String str1 = "hello world";
 String str2 = "hello world";
 
 // true,因为都指向同一内存地址(堆中的字符串常量池)
 System.out.println(str1 == str2); // true
 System.out.println(str1.equals(str2)); // true
 

2、针对同一字符串,==和equals有区别


// data.txt中存储的数据为一行hello world!
URL url = ClassLoader.getSystemResource("data.txt");
try( BufferedReader data = new BufferedReader(new FileReader(url.getPath()))){
     String str1 = data.readLine(); // hello world!
     //String str1 = data.readLine().inter(); // str1 == str2 为true
     String str2 = "hello world!";
     
     /**
      * 可以想象http请求、io读取数据时,字符串的生成都是StringBuilder完成的,
      * 但不会在常量池中生成对应的字符串
      */
     System.out.println(str1 == str2); // false
     System.out.println(str1.equals(str2)); // true
 } catch (Exception e){
     //do nothing
 }
 

三、 最后结论

针对字符串比较值相等时,一定用equals()方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值