在Java列表中使用字符串

huangapple go评论71阅读模式
英文:

Using Strings in Java Lists

问题

我知道Java在字符串操作方面有一种惯用的行为。由于字符串是不可变的,我们无法更改其内容。因此,我们不能编写:

String s = "test";
s.toUpperCase();

我们需要将s.toUpperCase()的结果赋值给一个新变量,例如:

String s1 = "test";
String s2 = s1.toUpperCase();

s1.toUpperCase并不是字符串s1被转换为大写后的字符串。它是一个新的字符串,具有自己的内存位置。因此,s1s2指向两个完全不同的内存位置,分别包含了"test"和"TEST"这两个字符串。

但是,如果我们不想使用新变量来分配新字符串,可以这样做:

String s = "test";
s = s.toUpperCase();

问题是:
我们能否对List<String>做类似操作?变量s表示具有值"test"的内存位置。因此,在s = s.toUpperCase();中,我们将s指向了新创建的字符串s.toUpperCase()的地址。在List<String> list中,如果list.get(0)(类似于s)指向一个字符串的位置,为什么我们不能像对s那样做呢?比如:list.get(0) = list.get(0).toUpperCase(),或者其他任何方式,就像数组的工作方式一样:

String[] array = {"test1", "test2"};
array[0] = array[0].toUpperCase();
英文:

I know that Java has an idiomatic behavior about String manipulation. Because strings are immutable we can not change the contents. So we can not write:

String s=&quot;test;&quot;
s.toUpperCase();

We need to assign the result of s.toUpperCase() to a new variable like:

String s1=&quot;test&quot;;
String s2=s1.toUpperCase;

s1.toUpperCase is not the the string s1 that changed to uppercase. It is a new string with its own memory location.
So s1 and s2 refer to two completed different memory locations with two copies of "test" and "TEST" literature.
But if we don't want to use a new variable to assign the new string then we can do this:

String s=&quot;test&quot;;
s=s.toUpperCase();

The question:
Can we do the same with a List<String>? The s variable represents a memory location that has the value of "test". So in the s=s.toUpperCase(); we drive the s to point to the new address of the created string s.toUpperCase() . If in a List&lt;String&gt; list the list.get(0) point (like s) to a location of string why we can't do the same as s like: list.get(0)=list.get(0).toUpperCase() or any other way for example like arrays work:

String[] array={&quot;test1&quot;,&quot;test2&quot;};
array[0]=array[0].toUpperCase();

答案1

得分: 3

list.get(0)=list.get(0).toUpperCase() 在Java语法和语义中是被禁止的。

大致上(详细情况更复杂,详见15.26.1. 简单赋值操作符 = 获取更多细节),赋值语句的左边必须是一个变量(或字段)。但是 list.get(0) 不是一个变量,它是一个值,因此你必须使用一些方法来修改列表中对应元素的值:

list.set(0, list.get(0).toUpperCase());
英文:

list.get(0)=list.get(0).toUpperCase() is forbidden by Java grammar and semantic.

Roughly (details are more complex, see 15.26.1. Simple Assignment Operator = for more details), the left hand part of an assignment must be a variable (or a field). But list.get(0) is not, it is a value, thus you have to use some method that will lets you modify the value of the corresponding element of the list:

list.set(0, list.get(0).toUpperCase())

huangapple
  • 本文由 发表于 2020年10月13日 19:52:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/64334712.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定