6

我遇到了一些困惑。

知道对象String不可变的。这意味着如果我从String类中调用一个方法,replace()那么原始内容String不会改变。相反,根据原始返回一个新的。 String但是,可以为相同的变量分配新值。

基于这个理论,我总是写a = a.trim()where ais a String一切都很好,直到我的老师告诉我,简单的a.trim()也可以使用。这搞砸了我的理论。

我和老师的理论一起测试了我的理论。我使用了以下代码:

String a = "    example   ";
System.out.println(a);
a.trim();      //my teacher's code.
System.out.println(a);
a = "    example   ";
a = a.trim();  //my code.
System.out.println(a);

我得到以下输出:

    example   
    example   
example

当我向老师指出时,她说,

这是因为我使用的是较新版本的 Java (jdk1.7) 并且a.trim() 可以在以前版本的 Java 中工作。

请告诉我谁有正确的理论,因为我完全不知道

4

4 回答 4

10

字符串在java中是不可变的。并trim() 返回一个新字符串,因此您必须通过分配它来取回它。

    String a = "    example   ";
    System.out.println(a);
    a.trim();      // String trimmed.
    System.out.println(a);// still old string as it is declared.
    a = "    example   ";
    a = a.trim();  //got the returned string, now a is new String returned ny trim()
    System.out.println(a);// new string

编辑:

她说这是因为我使用的是较新版本的 java (jdk1.7) 并且 a.trim() 在以前的 java 版本中有效。

请找一位新的java老师。这完全是一个没有证据的虚假陈述。

于 2014-01-04T06:07:23.757 回答
3

简单地使用“a.trim()”可能会在内存中修剪它(或者智能编译器会完全抛弃表达式),但结果不会被存储,除非你先将它分配给像你的“a = a.trim”这样的变量();"

于 2014-01-04T06:14:18.430 回答
2

字符串是不可变的,对它的任何更改都会创建一个新字符串。trim如果要使用从方法返回的字符串更新引用,则需要使用赋值。所以应该使用这个:

a = a.trim()
于 2014-01-04T06:08:04.367 回答
1

如果您想对字符串进行一些操作(例如修剪),则必须将字符串值存储在相同或不同的变量中。

String a = "    example   ";
System.out.println(a);
a.trim();      //output new String is not stored in any variable
System.out.println(a); //This is not trimmed
a = "    example   ";
a = a.trim();  //output new String is  stored in a variable
System.out.println(a); //As trimmed value stored in same a variable it will print "example"
于 2014-01-04T06:23:24.210 回答