English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
O método intern() da String no Java retorna a representação normalizada do objeto da string.
A sintaxe do método intern() da string é:
string.intern()
Aqui, string é um objeto da classe String.
Sem qualquer parâmetro
Retorna a representação normalizada da string
A string aninhada garante que todas as strings com o mesmo conteúdo usem a mesma memória.
Suponha que tenhamos duas strings:
String str1 = "xyz"; String str2 = "xyz";
Devido a ambos os str1and str2Com o mesmo conteúdo, portanto, essas duas strings compartilharão a mesma memória. O Java insere automaticamente strings literais.
Mas, se usar a palavra-chave new para criar uma string, essas strings não compartilharão a mesma memória. Por exemplo,
class Main { public static void main(String[] args) { String str1 = new String("xyz"); String str2 = new String("xyz"); System.out.println(str1 == str2); // false } }
A partir deste exemplo, pode-se ver que ambos os str1and str2Have the same content. However, they are not equal because they do not share the same memory.
In this case, you can manually use the intern() method to use the same memory for strings with the same content.
class Main { public static void main(String[] args) { String str1 = new String("xyz"); String str2 = new String("xyz"); //str1and str2do not share the same memory pool System.out.println(str1 == str2); // false //uses the intern() method //Now, str1and str2both share the same memory pool str1 = str1.intern(); str2 = str2.intern(); System.out.println(str1 == str2); // true } }
As you can see, str1and str2Have the same content, but they are not equal from the beginning.
Then, we use the intern() method so that str1and str2Use the same memory pool. After using intern(), str1and str2Equal.