Não deveria fazer `String s = new String(“a new string”);` em Java, mesmo com internação automática de strings?

StackOverflow https://stackoverflow.com//questions/10666537

Pergunta

Ok, esta pergunta é uma extensão desta pergunta

Sequências Java:"String s = new String("bobo");"

A pergunta acima fez a mesma pergunta que esta, mas tenho um novo ponto de dúvida.

De acordo com Effective Java e as respostas da pergunta acima, devemos não fazer String s = new String("a new string");, porque isso criará objetos desnecessários.

Não tenho certeza sobre esta conclusão, porque acho que Java está fazendo internação automática de strings, o que significa que para uma string, de qualquer forma, há apenas uma cópia dela na memória.

Então vamos ver String s = new String("a new string");.

"a new string" já é uma string que foi criada na memória.

Quando eu faço String s = new String("a new string");, então o s é também "a new string".Então de acordo com automatic string interning, s deve ser apontado para o mesmo endereço de memória de "a new string", certo?

Então como podemos dizer que criamos objetos desnecessários?

Foi útil?

Solução


String a = "foo"; // this string will be interned
String b = "foo"; // interned to the same string as a
boolean c = a == b; //this will be true
String d = new String(a); // this creates a new non-interned String
boolean e = a == d; // this will be false
String f = "f";
String g = "oo";
String h = f + g; //this creates a new non-interned string
boolean i = h == a // this will be false
File fi = ...;
BufferedReader br = ...;
String j = br.readLine();
boolean k = a == j; // this will always be false. Data that you've read it is not automatically interned

Outras dicas

Você pode querer ler mais sobre Conjunto literal de strings em JVMs.Uma pesquisa rápida no Google me indicou este artigo:http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3o que parece bastante válido.

Além disso, você pode estar interessado em pooling de literais inteiros, bem como em pooling de outros literais em Java.

usar "=" em vez de "=new String" é melhor, pois pode resultar em uma única instância em vez de várias instâncias.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top