简体   繁体   English

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

[英]Efficient way to assign a value to a String variable in a loop

I am assigning a value to a String variable ( name ) in a while loop. 我在while循环中为String变量( name )分配一个值。 I understand that the String data type is immutable and if I assign 1000 different values to the same String variable it will create a 1000 references in the String Constant pool. 我知道String数据类型是不可变的,如果将1000个不同的值分配给同一个String变量,它将在String常量池中创建1000个引用。 However, I am not able to think of any other efficient way of doing this... please advice... 但是,我无法想到任何其他有效的方式来完成此操作。

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++;         
}

You should be good with name = reader.readLine() and that's a good practice. 您应该对name = reader.readLine() ,这是一个好习惯。 However since you asked about string pool in java, here is a nice explanation on when to use direct string assignment vs new String(...) and how it affects your heap - http://www.thejavageek.com/2013/06/19/the-string-constant-pool/ 但是,由于您询问了Java中的字符串池,因此以下是有关何时使用direct string assignment vs new String(...)以及它如何影响堆的很好的解释-http: //www.thejavageek.com/2013/06 / 19 /的字符串常量池/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM