为了账号安全,请及时绑定邮箱和手机立即绑定

java中的字符串池,编译时与运行时字符串评估

java中的字符串池,编译时与运行时字符串评估

一只萌萌小番薯 2023-06-21 14:45:49
我正在研究获得我的 OCA 考试并坚持这个 java 字符串池概念。考虑以下几点:public static void main(String[] args) {    String s1 = "Hello";                // since s1 and s2 are the same literal at compile-time, therefore they will be string pooled    String s2 = "Hello";    String s3 = "Hello".trim();    StringBuilder sb1 = new StringBuilder("Hello");     // although they are the same string, == only checks for object equality    StringBuilder sb2 = new StringBuilder("Hello");    System.out.println(s1 == s2);       // true    System.out.println(s1 == s3);       // true    System.out.println(sb1 == sb2);     // false}s1并且s2在字符串中相同并且在对象中也相同,因为因为它是相同的字符串文字,JVM 将在编译时将字符串池s1和。s2现在,s3是在运行时计算的,因此应该返回一个新字符串。因此,s1 == s3应该是假的,但事实并非如此。为什么?我的一个理论是该trim()方法首先检查是否有要删除的空白,如果没有,则简单地返回自身。这可以解释为什么s1 == s3,但我不确定。
查看完整描述

3 回答

?
慕哥6287543

TA贡献1831条经验 获得超10个赞

你是对的。如果trim()方法不改变值,那么将返回原始实例。如果所有“Hello”都更改为“Hello”,则 s3 将不等于 s1,因为 trim() 会删除空格并返回一个新的字符串实例。



查看完整回答
反对 回复 2023-06-21
?
慕的地8271018

TA贡献1796条经验 获得超4个赞

如果您查看该trim()方法的源代码,这是正确的,您会看到在删除空格后substring(start, end)调用了该方法。否则,如果没有空格,则this返回相同的实例。


public String trim() {

   int len = value.length;

   int st = 0;

   char[] val = value;    /* avoid getfield opcode */


   while ((st < len) && (val[st] <= ' ')) {

       st++;

   }

   while ((st < len) && (val[len - 1] <= ' ')) {

       len--;

   }

   return ((st > 0) || (len < value.length)) ? substring(st, len) : this;

 }

这st是删除空格后的起始索引,len是新的长度。


现在,如果字符串之前或之后有任何空格:


String s1 = "hello "; //<-- whietspace at the end

System.out.println(s1.trim() == "hello");

输出与方法调用时的输出false相同。如果和不相同,则子字符串返回一个新的 String 实例:substring()trim()beginIndexendIndex


return ((beginIndex == 0) && (endIndex == value.length)) ? this

                : new String(value, beginIndex, subLen);

因此,在删除空格(如果有)之后, 和beginIndex显然endIndex会发生变化,并且new String()将返回一个实例。


查看完整回答
反对 回复 2023-06-21
?
12345678_0001

TA贡献1802条经验 获得超5个赞

这是 trim() 的源代码。如果没有要删除的空格,则返回this. 所以它与您trim编辑的参考文献相同。


public String trim() {

    int len = value.length;

    int st = 0;

    char[] val = value;    /* avoid getfield opcode */


    while ((st < len) && (val[st] <= ' ')) {

        st++;

    }

    while ((st < len) && (val[len - 1] <= ' ')) {

        len--;

    }

    return ((st > 0) || (len < value.length)) ? substring(st, len) : this;

}


查看完整回答
反对 回复 2023-06-21
  • 3 回答
  • 0 关注
  • 96 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信