字符串 - 它们如何工作? [英] Strings - How do they work?

查看:119
本文介绍了字符串 - 它们如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String 如何在Java中使用对象?术语不可变如何完全适用于字符串对象?为什么我们不通过某种方法看到修改后的字符串,虽然我们操作原始的字符串对象值?

How do String objects work in Java? How does term "immutable" exactly apply to string objects? Why don't we see modified string after passing through some method, though we operate on original string object value?

推荐答案

一个字符串有私人决赛 char [] 。创建新的String对象时,也会创建并填充该数组。它不能在以后[从外部]访问或修改[实际上它可以用反射完成,但我们将把它放在一边]。

a String has a private final char[] . when a new String object is created, the array is also created and filled. it cannot be later accessed [from outside] or modified [actually it can be done with reflection, but we'll leave this aside].

它是不可变的因为一旦创建了一个字符串,其值就无法更改,cow字符串将始终具有值cow。

it is "immutable" because once a string is created, its value cannot be changed, a "cow" string will always have the value "cow".

我们看不到修改后的字符串,因为它是不可变的,同样的对象永远不会改变,无论你用它做什么[除了用反射修改它]。所以cow+horse会创建一个 new String对象,而不是修改最后一个对象。

We don't see modified string because it is immutable, the same object will never be changed, no matter what you do with it [besides modifying it with reflection]. so "cow" + " horse" will create a new String object, and NOT modify the last object.

如果你定义:

void foo(String arg) {
  arg= arg + " horse";
}

您致电:

String str = "cow";
foo(str);

str 这里的电话不是修改[因为它是同一个对象的原始引用!]当你改变 arg 时,你只需将它改为引用另一个String对象,并且没有改变实际的原始对象。所以 str ,将是同一个未更改的对象,仍然包含cow

the str where the call is is not modified [since it is the original reference to the same object!] when you changed arg, you simply changed it to reference another String object, and did NOT change the actual original object. so str, will be the same object, which was not changed, still containing "cow"

如果您仍想更改String对象,可以使用反射来完成。但是,未经修改并且可能会产生一些严重的副作用:

if you still want to change a String object, you can do it with reflection. However, it is unadvised and can have some serious side-affects:

    String str = "cow";
    try { 
    Field value = str.getClass().getDeclaredField("value");
    Field count = str.getClass().getDeclaredField("count");
    Field hash = str.getClass().getDeclaredField("hash");
    Field offset = str.getClass().getDeclaredField("offset");
    value.setAccessible(true);
    count.setAccessible(true);
    hash.setAccessible(true);
    offset.setAccessible(true);
    char[] newVal = { 'c','o','w',' ','h','o','r','s','e' };
    value.set(str,newVal);
    count.set(str,newVal.length);
    hash.set(str,0);
    offset.set(str,0);
    } catch (NoSuchFieldException e) {
    } catch (IllegalAccessException e) {}
    System.out.println(str);
}

这篇关于字符串 - 它们如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆