Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为循环中的字符串变量赋值的有效方法_Java_String - Fatal编程技术网

Java 为循环中的字符串变量赋值的有效方法

Java 为循环中的字符串变量赋值的有效方法,java,string,Java,String,我正在while循环中为字符串变量(name)赋值。我知道字符串数据类型是不可变的,如果我给同一个字符串变量分配1000个不同的值,它将在字符串常量池中创建1000个引用。然而,我想不出任何其他有效的方法来做到这一点。。。请建议 while ((name = reader.readLine()) != null) { //Add each character in the name to the list for (char c : name.toCharArray()) {

我正在while循环中为字符串变量(
name
)赋值。我知道字符串数据类型是不可变的,如果我给同一个字符串变量分配1000个不同的值,它将在字符串常量池中创建1000个引用。然而,我想不出任何其他有效的方法来做到这一点。。。请建议

while ((name = reader.readLine()) != null) {
    //Add each character in the name to the list
    for (char c : name.toCharArray()) {
        if (c != ' ') {  
            list.add(Character.toLowerCase(c));                     
        }
    }               
    namesCount++;         
}

您应该善于使用
name=reader.readLine()
,这是一个很好的做法。然而,既然您询问了java中的字符串池,这里有一个很好的解释,说明了何时使用
直接字符串分配与新字符串(…)
以及它如何影响堆-

您应该熟悉
name=reader.readLine()
,这是一个很好的实践。然而,既然您询问了java中的字符串池,这里有一个很好的解释,说明了何时使用
直接字符串分配与新字符串(…)
以及它如何影响堆-

什么是
列表
?我在这里看不到任何字符串。全部为charactersList=new ArrayList()
为循环中的字符串变量赋值的有效方法
字符串在哪里?你说的是abt
name=reader.readLine()
line吗?Suresh Atta,Rehman:是的,名称就是我指的字符串变量。什么是
list
?我在这里看不到任何字符串。全部为charactersList=new ArrayList()<代码>为循环中的字符串变量赋值的有效方法字符串在哪里?你说的是abt
name=reader.readLine()
line吗?Suresh Atta,Rehman:是的,名称就是我指的字符串变量。